TouchBegan方法无法在swift3中运行

时间:2017-05-16 07:23:52

标签: ios iphone swift keyboard keyboard-events

我想在点击屏幕上的任何位置时关闭键盘。为此,我使用了touchbegan方法,但没有调用此方法。

5 个答案:

答案 0 :(得分:1)

您需要指定UITapGestureRecogniser来查看和关闭键盘。

在viewdidLoad()

let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.dismissKeybord(_:)))
        tap.numberOfTapsRequired = 1
        self.view.addGestureRecognizer(tap)

在dismissKeybord

func dismissKeybord(_ sender:UITapGestureRecognizer) {
        self.view.endEditing(true)
}

答案 1 :(得分:0)

为我工作。显示键盘与textfields的联系。隐藏其他所有内容。

class LoginController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var userLogin: UITextField!
    @IBOutlet weak var userPassword: UITextField!

    override func viewDidLoad() {

      userLogin.delegate = self
      userPassword.delegate = self

      //For scrolling the view if keyboard on
      NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillShow),
                                             name: NSNotification.Name.UIKeyboardWillShow, object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillHide),
                                             name: NSNotification.Name.UIKeyboardWillHide, object: nil)

      super.viewDidLoad()
    }

    // OTHER METHODS

    var keyBoardAlreadyShowed = false //using this to not let app to scroll view
    //if we tapped UITextField and then another UITextField

    func keyboardWillShow(notification: NSNotification) {
      if !keyBoardAlreadyShowed {
         view.frame.origin.y -= 50
         keyBoardAlreadyShowed = true
      }
    }

    func keyboardWillHide(notification: NSNotification) {
      view.frame.origin.y += 50
      keyBoardAlreadyShowed = false
    }

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

您需要设置delegatesobservers

答案 2 :(得分:0)

如果您的触摸不被其他视图吃掉,那么我想这会起作用

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if touches.first != nil {
                view.endEditing(true)
        }
   }

答案 3 :(得分:0)

斯威夫特3: -

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

答案 4 :(得分:0)

最近我的案子很有用。也应该适合你。

  1. 创建 UITapGestureRecognizer
  2. 在以下代码中 endEditing 选择器方法中,只需调用 self.view.endEditing(true)即可。
  3. (请注意,参数true是动画的值)

    class MyViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(endEditing))
            tapper.cancelsTouchesInView = false
            self.view.addGestureRecognizer(tapGestureRecognizer)
        }
    
        func endEditing() {
            self.view.endEditing(true)
        }
    }