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

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

问题描述

我有一个 UITableView ,其中 UITextField s作为单元格。我想在触及 UITableView 的背景时关闭键盘。我试图通过创建一个 UIButton 的大小 UITableView 并将其放在<$ c后面$ C>的UITableView 。唯一的问题是,即使触摸在UITableView上, UIButton 也能捕获所有触摸。我做错了什么?

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 object(默认情况下,这将在单击时检测手势,因此不需要进一步自定义),指定触发手势时的目标/动作,然后将手势识别器对象附加到表视图。

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天全站免登陆