【问题标题】:Dismissing Keyboard for UITextField关闭 UITextField 的键盘
【发布时间】:2017-03-28 23:55:28
【问题描述】:

我是 Swift 新手,最近我在学习 UITextField 以及它是如何委托的。我想知道是否有一种简单的方法可以在敲击键盘外部(视图中的其他位置)时关闭键盘。目前,我正在使用UITapGestureRecognizer 来执行此操作。它有效,但我想知道是否有更简单的方法来做到这一点。

【问题讨论】:

标签: ios swift keyboard uitextfield


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    1. 设置UITextField的代理,如UITableviewDataSource,Delegate。在viewDidLoad()中写yourTextFieldDelegate.delegate = self

    2. 然后,编写这个函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多