要设置的键盘代码已设置但仍无法正常工作?

时间:2017-01-23 21:57:51

标签: ios swift

我已经完成了我想到的所有事情,但是当我运行此代码时,键盘会出现但仍然无法通过点击或返回按钮消失。有人能帮我吗?

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var Label: UILabel!
    @IBOutlet var Label2: UILabel!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.delegate = self          
    }        

    //Hide keyboard when user touches outside keyboard
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    //Presses return key
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return(true)
    }
}

2 个答案:

答案 0 :(得分:0)

无法在评论中显示图片,因此我创建了答案。我能够轻松地完成这项工作。我添加了一个控制器,添加了自定义类,插座,几乎添加了您的确切代码。有时我忘记添加自定义类。也许就是这样。

Setting the Custom Class

答案 1 :(得分:0)

最好不要使用touchesBegan。一种肯定会起作用的方法:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var Label: UILabel!
    @IBOutlet var Label2: UILabel!
    @IBOutlet weak var textField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.delegate = self

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.didTapBackground))
        tapGestureRecognizer.cancelsTouchesInView = false
        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(tapGestureRecognizer)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func didTapBackground() {
        view.endEditing(true)
    }

    //Presses return key

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return(true)
    }

}

请注意,我还将cancelTouchesInView设置为false,让其他按钮或UITapGestureRecognizers正确完成工作。