ios - 在 UITextField 外部点击以停止编辑

标签 ios swift uitextfield tap

当我在我的 UITextField 外面敲击时清除它的内容并隐藏键盘它的 react 就像我点击了 return并触发与命中相关的操作 return .这对我来说似乎很违反直觉。

清除文本字段并关闭键盘是我想要的,但不是 amountEntered(_:)调用.. 我希望能够在我点击 textField 之外时中止 任何操作

我该如何改变它?

enter image description here

所有与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 结束编辑。这是因为您将其设置为事件 .editingDidEndIBAction

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/

相关文章:

ios - 在 Swift 中创建类和结构来表示 JSON 对象

Swift:计算将 SKSpriteNode 旋转多少以使其指向 CGPoint

ios - 从下到上逐渐填充一个圆圈swift2

swift - Swift 中的简单滑动 - xCode 6

ios - GPUImage 灰度和对比度过滤器生成内存警告

ios - iOS7 中一致的后台获取?

ios - Objective-C : How to remove a white background from a JPG image without losing edge quality

ios - UIAlertController 中的自定义文本字段

ios - swift 。设置文本字段中输入的格式

objective-c - 如何将一个 UIDatePicker 用于多个 UITextFields?