这个问题在这里已经有了答案:
iOS - Dismiss keyboard when touching outside of UITextField
(38 个回答)
6年前关闭。
我有一些 UITextFields 可以打开键盘。
我的问题是,如何检测不在任何 UITextField 中的屏幕触摸
我需要的伪代码:
if(screen is touched)
if(touched view is NOT a UITextField)
[self.view endEditing:YES];
有没有简单的方法来实现这一点?或者在未触摸 UITextField 时隐藏键盘的另一种更简单的方法?
谢谢!
最佳答案
只需添加 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];
}
关于ios - 检测不在 UITextField 上的触摸(使键盘隐藏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801406/