通过触摸 UITableView 的背景关闭键盘 [英] Dismiss keyboard by touching background of UITableView

查看:29
本文介绍了通过触摸 UITableView 的背景关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITableView,其中 UITextFields 作为单元格.当触摸 UITableView 的背景时,我想关闭键盘.我试图通过创建一个 UIButton 大小的 UITableView 并将它放在 UITableView 后面来做到这一点.唯一的问题是 UIButton 即使在 UITableView 上触摸时也会捕获所有触摸.我做错了什么?

I have a UITableView with UITextFields as cells. I would like to dismiss the keyboard when the background of the UITableView is touched. I'm trying to do this by creating a UIButton the size of the UITableView and placing it behind the UITableView. The only problem is the UIButton is catching all the touches even when the touch is on the UITableView. What am I doing wrong?

谢谢!

推荐答案

这可以通过创建一个 UITapGestureRecognizer 对象(默认情况下,这将在单击时检测手势",因此无需进一步自定义),指定触发手势时的目标/操作,然后将手势识别器对象附加到您的表视图.

This is easily done by creating a UITapGestureRecognizer object (by default this will detect a "gesture" on a single tap so no further customization is required), specifying a target/action for when the gesture is fired, and then attaching the gesture recognizer object to your table view.

例如也许在您的 viewDidLoad 方法中:

E.g. Perhaps in your viewDidLoad method:

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];

hideKeyboard 方法可能如下所示:

- (void) hideKeyboard {
    [textField1 resignFirstResponder];
    [textField2 resignFirstResponder];
    ...
    ...
}

请注意,触摸 UITextField 对象内部时不会触发手势.它虽然在 UITableView 背景、页脚视图、标题视图和单元格内的 UILabels 等上被触发.

Note that the gesture is not fired when touching inside a UITextField object. It is fired though on the UITableView background, footer view, header view and on UILabels inside cells etc.

这篇关于通过触摸 UITableView 的背景关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆