【问题标题】:How to dismiss keyboard by tapping on screen如何通过点击屏幕关闭键盘
【发布时间】:2017-01-15 20:45:48
【问题描述】:

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

override func viewDidLoad() {
    super.viewDidLoad()


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

    view.addGestureRecognizer(tap)

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

【问题讨论】:

  • 能否也显示您的dismissKeyboard方法代码?

标签: ios swift keyboard


【解决方案1】:

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

   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)
   }

然后每当我需要引用 .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

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

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

【讨论】:

    【解决方案2】:
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismiss:"))
    view.addGestureRecognizer(tap)
    
    func dismiss(gest : UITapGestureRecognizer){
            view.endEditing(true)
        }
    

    这很好用,试试吧。

    【讨论】:

      【解决方案3】:

      你可以试试这个,它非常简单的解决方案,经常用于快速关闭键盘。

      添加这个函数就行了。

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

      【讨论】:

        猜你喜欢
        • 2011-08-08
        • 2019-01-10
        • 1970-01-01
        • 2020-11-10
        • 1970-01-01
        • 2011-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多