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

标签 ios objective-c keyboard

<分区>

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

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

我需要的伪代码:

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

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

谢谢!

最佳答案

只需将 UITapGestureRecognizer 添加到您的 View 并使用 [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/

上一篇:ios - 如何在 Xcode 7 中嵌入 Cocoa Touch Framework

下一篇:ios - 在没有完整 mip 链的情况下启用 mipmapping

相关文章:

ios - 强制 FBSDK ShareDialog React Native 自动使用浏览器

iphone - objective-c 的奇怪行为

ios - 在 UITableView 中用手指在屏幕上绘图

jquery - 使用键盘控制 jQuery Easing

ios - 如何在 EventKit (swift 4) 中添加正确的事件时间?

ios - Swift:复制文件会出现 Cocoa 错误 262

ios - 为什么我的 IOS 应用程序拒绝 cdvfile ://and file:///links?

objective-c - 为 NSTableView 中的行着色

iphone - 这是UIKit错误吗?

python - 我无法使用箭头键在 pygame 中移动图像