我有一个文本字段,通过设置.autocapitalizationType = .none禁用大写字母,在shouldChangeCharactersIn range中,我用小写字母替换任何大写字母
通过using this answer
只强制使用小写字母可以很好地工作,但是我添加到.editingChanged的目标方法停止工作。
为什么.editingChanged停止工作?

let emailTextField: UITextField = {
    let textField = UITextField()
    return textField
}()

let userNameTextField: UITextField = {
    let textField = UITextField()
    textField.autocapitalizationType = .none
    textField.addTarget(self, action: #selector(printSomething), for: .editingChanged)
    return textField
}()

@objc func printSomething() {
    // as I type inside the usernameTextField this no longer prints
    print("something")
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // only change characters for username textfield
    if textField == userNameTextField {

        userNameTextField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased())
        return false
    }
    return true
}

最佳答案

问题是您的userNameTextField声明。初始化时没有self。您需要将其声明更改为lazy

lazy var userNameTextField: UITextField = {
    let textField = UITextField()
    textField.autocapitalizationType = .none
    textField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    return textField
}()

我还将删除范围中的shouldChangeCharacters,并在editingChanged方法中执行所有字符操作:
@objc func editingChanged(_ textField: UITextField) {
    print(textField.text!)
    textField.text = textField.text!.lowercased()
}

关于ios - iOS -Textfield的shouldChangeCharactersIn范围禁用.editingChanged的target方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54926674/

10-14 23:08