当我点击
UITextField
外部以清除其内容并隐藏键盘时,它的反应就像我点击 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
结束编辑时被调用。这是因为您将其设置为事件 IBAction
的 .editingDidEnd
。
在
hideKeyboard()
中,您在 self.view
上设置了一个点击手势,链接到 dismissKeyboard()
,执行 view.endEditing(true)
。
这基本上会导致所有急救人员辞职;意味着 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 = ""
}
}
您可以在
view.endEditing(true)
中使用 Tap action responder
,这将调用您的 textFieldDidEndEditing:
委托方法。而不是 textFieldShouldReturn
的 UITextField
代表。
我遇到了同样的问题,然后在 Google 上搜索,最终修复了 Mac