当我在我的 UITextField
外面敲击时清除它的内容并隐藏键盘它的 react 就像我点击了 return
并触发与命中相关的操作 return
.这对我来说似乎很违反直觉。
清除文本字段并关闭键盘是我想要的,但不是 amountEntered(_:)
调用.. 我希望能够在我点击 textField
之外时中止 任何操作
我该如何改变它?
所有与TextField
相关的代码:
override func viewDidLoad() {
super.viewDidLoad()
amountEnteredTextField.delegate = self
registerForKeyboardNotifications()
self.hideKeyboard()
}
func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
@IBAction func amountEntered(_ sender: UITextField) {
if allowNewAmount == true {
if amountEnteredTextField.text == "" {
return
}
amountLabel.text = amountEnteredTextField.text
amountEnteredTextField.text = ""
}
}
调试后,问题似乎出在这个用于隐藏键盘的扩展上:
extension UIViewController {
func hideKeyboard() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
最佳答案
所以看起来你的 amountEntered(_:)
在任何时候调用 amountEnteredTextField
结束编辑。这是因为您将其设置为事件 .editingDidEnd
的 IBAction
。
在 hideKeyboard()
中,您已经在链接到 dismissKeyboard()
的 self.view
上设置了点击手势,它执行 view.endEditing(真)
。
这基本上会让任何第一响应者辞职;这意味着 amountEnteredTextField
编辑结束,因此当您点击外部时调用 amountEntered(_:)
。
如果你想确保 amountEntered(_:)
只在用户点击键盘的返回键时被调用,那么你应该稍微修改你的设计:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
/*
Check to see which is the delegated textField.
Basically to do textField-specific logic.
Helps mostly if you have multiple textFields
*/
if textField == amountEnteredTextField {
amountEntered()
}
//resign textField
textField.resignFirstResponder()
return true
}
func amountEntered() {
if allowNewAmount, amountEnteredTextField.text != "" {
amountLabel.text = amountEnteredTextField.text
amountEnteredTextField.text = ""
}
}
关于ios - 在 UITextField 外部点击以停止编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433600/