在文本字段外触摸时如何关闭键盘?

How to dismiss keyboard when touch outside the textfield?

我有这样的结构:

 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 的宽度相同。

"Another View" 宽度与视图不同。在 "another 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

}

试试下面的代码,它在用户触摸 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)