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

Mil*_*tle 2 uitextfield ios swift2 swift3

我有这个结构:

 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
Run Code Online (Sandbox Code Playgroud)

视图与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

}
Run Code Online (Sandbox Code Playgroud)

Pat*_*gar 6

当用户触摸uiviewcontroller的视图时,尝试下面隐藏键盘的代码,代码在swift 3.0中,希望它能帮到你.

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

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