提问者:小点点

关闭 UITextField 的键盘


我是Swift的新手,最近我学习了UITextField及其代理。我想知道是否有一种简单的方法可以在键盘外部(视图中的其他位置)录制时关闭键盘。目前,我正在使用UIMapGestureRecognizer执行此操作。这是可行的,但我想知道是否有更简单的方法。


共2个答案

匿名用户

您可以使用此方法通过点击屏幕上的任何位置来关闭键盘

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}

但是一定要事先设置代理。

匿名用户

> < li>

将< code>UITextField的委托设置为< code>UITableviewDataSource,Delegate。在< code>viewDidLoad()中写入< code > yourtextfield delegate . delegate = self

然后,编写此函数:

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