如何通过点击屏幕关闭键盘

Mar*_*eli 1 keyboard ios swift

我正在快速寻找一个简单的解决方案,以添加点击屏幕上任意位置并关闭键盘的功能。我在这里阅读了很多答案,但它们都为我抛出了错误。我之前用过的一个是这样的:

override func viewDidLoad() {
    super.viewDidLoad()


   let tap: UITapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(ViewController.dismissKeyboard))

    view.addGestureRecognizer(tap)
Run Code Online (Sandbox Code Playgroud)

这适用于我的一个项目,但似乎不适用于任何其他项目。每当我尝试将其添加到其他项目时,我都会收到错误类型“ViewController”没有成员“dismissKeyboard”。

小智 5

您需要在对它的任何引用之上添加一个方法。我将此代码放在文件的开头:

   func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status and drop into background
    view.endEditing(true)
   }
Run Code Online (Sandbox Code Playgroud)

然后每当我需要引用 .dismissKeyboard 时,我都会在 viewDidLoad() 中使用它:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)  // Allows dismissal of keyboard on tap anywhere on screen besides the keyboard itself
Run Code Online (Sandbox Code Playgroud)

并确保将“LoginViewController”替换为当前的视图控制器。根据您的示例,这只是“ViewController”

如果您正在寻找更深入的答案,请参阅 7KV7:https ://stackoverflow.com/a/5711504/6312593