【问题标题】:How to dismiss keyboard when touch outside the textfield?在文本字段外触摸时如何关闭键盘?
【发布时间】:2017-01-18 07:39:45
【问题描述】:

我有这个结构:

 ViewController
     |
  MainView  <-- Give a Tap value =1
     |
  ScrollView
     |
    View <-- give a Tag value =2
      |
     another View use to contain textFields  <-- give a tap value =3

View 的宽度与 Scrollview 和 MainView 相同。

“另一个视图”的宽度与视图不同。在“另一个视图”中,我有几个文本字段。

问题:在视图上或文本字段外触摸,键盘不会关闭。

我已经为键盘实现了这个,但它不起作用。

 override func toucheBegan(touches: Set<UITouch>, withEvent event:UiEvent?){

      if (view.tag == 1) {

            //- this refer to main view
            view.endEditing(true)

      } else {

         //- this refer to the other view.
      view.endEditing(true)

      }

--Upate:<br/>

  override func toucheBegan(touches: Set<UITouch>, withEvent event:UiEvent?){

      self.view.endEditing(true)  // with or without self

}

【问题讨论】:

  • 您没有检查正确的视图标签。您正在检查主视图标签
  • 你在视图上设置了 userInteractionEnabled 吗?
  • 我是否需要为每个视图(主视图、视图、另一个视图)放置一个标签值?仅当主视图位于视图后面时,如何在用户可以触摸视图和另一个视图时引用哪个视图。已为 3 个视图设置了 UserInteractionEnabled。

标签: ios swift2 swift3 uitextfield


【解决方案1】:

尝试下面的代码,当用户触摸uiviewcontroller的视图时隐藏键盘,代码在swift 3.0,希望对你有帮助。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true) //This will hide the keyboard
}

否则您必须为该特定视图设置 uitapgesturerecognizer,或者您可以使该视图 uicontrol 并设置 touchupinside 事件, 您所要做的就是从上述任何事情中调用 self.view.endEditing(true)

【讨论】:

  • 第一个选项在使用 touchesBegan 时不起作用。为什么?第二个选项怎么做?
  • @MilkBottle 将 uitapgesturerecognizer 添加到您想要在触摸时隐藏键盘的视图中。并将 self.view.endEditing(true) 添加到您在 tapgesturere 上设置的功能
猜你喜欢
  • 2011-07-15
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2018-11-08
  • 2015-11-23
相关资源
最近更新 更多