输入一个字符后关闭键盘

Dismiss keyboard after one character typed

我想在输入一个字符后关闭键盘。我试试这个代码:

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

    if string == "" {
        return true
    }

    if let characterCount = textField.text?.count {
        if characterCount == 1 {
            return textField.resignFirstResponder()
        }
    }
    return true
}

但是只有在输入 2 个字符后键盘才会关闭并显示此代码。我希望在键入一个字符后关闭键盘。

试试这个!

override func viewDidLoad() {
    super.viewDidLoad()
       
    let textField = UITextField()
    textField.addTarget(self, action: #selector(textField_editingChanged), for: .editingChanged)
    view.addSubview(textField)
        
}
    
@objc func textField_editingChanged(sender:UITextField) {
    if sender.text?.count == 1 {
        view.endEditing(true)
    }
}