检测不在 UITextField 上的触摸(隐藏键盘)

Detecting a touch NOT on a UITextField (to make keyboard hide)

我有一些 UITextFields 可以打开键盘。

我的问题是,如何检测屏幕上不在任何 UITextField 中的触摸

我需要的伪代码:

if(screen is touched)
   if(touched view is NOT a UITextField)
      [self.view endEditing:YES];

有没有简单的方法可以做到这一点?或者在未触摸 UITextField 时隐藏键盘的另一种更简单的方法?

谢谢!

您实际上可以使用 touches begind 方法。

查看文档here

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

来自文档-

If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, if only as stub (empty) implementations.

只需将 UITapGestureRecognizer 添加到您的视图并使用 [self.view endEditing:YES];

- (void)addTapGesutre {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]  initWithTarget:self
                                                                             action:@selector(handleTapGesture:)];
    tapGesture.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tapGesture];
}

- (void)handleTapGesture:(UITapGestureRecognizer *)tap {
    if (tap.state == UIGestureRecognizerStateEnded) {
        [self keyboardDismiss];
    }
}

- (void)keyboardDismiss {
    [self.view endEditing:YES];
}