简体   繁体   English

无法从UITextField退出FirstResponder

[英]Unable to resignFirstResponder from UITextField

Do you know(can you see) why I can not resign from FirstResponder and hide the keyboard? 您知道(看到)为什么我不能从FirstResponder辞职并隐藏键盘吗?

FYI: Xcode 9 仅供参考:Xcode 9

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var text: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.text.delegate = self
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(tap)
    }

    var keyboardInputEnabled = true
    @objc func tapFunction(sender:UITapGestureRecognizer) {
        if self.keyboardInputEnabled {
            self.text.becomeFirstResponder()
        }else{
            self.view.endEditing(true)
            self.text.resignFirstResponder()
        }
        self.keyboardInputEnabled = !self.keyboardInputEnabled
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return self.keyboardInputEnabled
    }

    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        return self.keyboardInputEnabled
    }

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return self.keyboardInputEnabled
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Because textFieldShouldEndEditing return false the second time you run tapFunction which prevent it to end editing mode. 因为textFieldShouldEndEditing在您第二次运行tapFunction时返回false,这会阻止它tapFunction编辑模式。

Taken from this 取自

Normally, you would return true from this method to allow the text field to resign the first responder status. 通常,您将从此方法返回true,以允许文本字段退出第一响应者状态。 You might return false, however, in cases where your delegate detects invalid contents in the text field. 但是,如果您的委托人在文本字段中检测到无效内容,则可能返回false。 Returning false prevents the user from switching to another control until the text field contains a valid value. 返回false将阻止用户切换到另一个控件,直到文本字段包含有效值为止。

Try 尝试

self.view.endEditing(true) for disabling keyboard self.view.endEditing(true)用于禁用键盘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM