且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当用户按下其他控件/空格时,如何取消聚焦 UITextFields?

更新时间:2023-11-18 13:23:28

我总是把这个添加到我的 ViewController

I always add this to my ViewController

override func viewDidLoad()
{
    super.viewDidLoad()

    // other stuff

    // but to stop editing when the user taps anywhere on the view, add this gesture recogniser
    let tapGestureBackground = UITapGestureRecognizer(target: self, action: #selector(self.backgroundTapped(_:)))
    self.view.addGestureRecognizer(tapGestureBackground)
}

func backgroundTapped(_ sender: UITapGestureRecognizer)
{
    self.endEditing(true)   
}