为什么 UITextField 在输入的字符串末尾添加空格?

Why UITextField added whitespaces at the end of inputed strings?

经过调试,我发现 UITextField 会在我从剪贴板粘贴的字符串中添加空格。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var input: String
        let newString = string.trimmingCharacters(in: .whitespacesAndNewlines)   // newString = "123"
        if let oldString = textField.text {                                      // oldString = "456"
            input = oldString
            input.insert(contentsOf: newString, at: input.index(input.startIndex, offsetBy: range.location))  // rang.location = 2, input = "4 123 56" but it supposed to be "412356"
        } else {
            input = newString
        }
        return true  
}

我有两个问题:
1-为什么只有粘贴第二次和更多次才会发生?
2- 如何避免将这些空格添加到粘贴的字符串中?

您可能正在观察 smartInsertDeleteType 属性 的影响。您可以这样更改:

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.smartInsertDeleteType = .no
    }
}