在文本区域外触摸时如何关闭键盘?

时间:2017-01-18 07:39:46

标签: ios swift2 swift3 uitextfield

我有这个结构:

 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

视图的宽度与Scrollview和MainView相同。

&#34;另一种观点&#34;宽度与View不同。在&#34;另一个视图&#34;中,我有几个文本域。

问题:触摸View或文本字段外,键盘不会消失。

我已经为键盘实现了这个功能,但它没有用。

 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

}

1 个答案:

答案 0 :(得分:6)

当用户触摸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)

相关问题