UITableView - 外部触摸第一响应者 [英] UITableView - resign first responder on outside touch
问题描述
我有一个UITableView和一个相关的UITableViewController。但是,我已经修改了表,以具有一个textfield子视图的视图。
I have a UITableView with an associated UITableViewController. However, I've modified the table to also have a view with a textfield subview.
像往常一样,当用户点击完成(简单)时,以及当他们触摸屏幕上除文本框之外的任何其他位置时,键盘消失
As always, I want the keyboard to disappear when the user hits 'done' (easy) and when they touch anywhere else on screen other than the textfield (hard, stuck!).
实现这个的正常方法是将类更改为UIControl,所以它可以处理操作...但我不能为我的UITableView / UITableViewController组合。
The normal way to achieve this is to change the class to UIControl so it can handle actions... but I can't do this for my UITableView/UITableViewController combination.
我如何解决这个问题?
How can I solve this problem?
推荐答案
U可以通过向您的视图添加 UITapGestureRecognizer
。
例如,如果u不想在tableView u中启用行选择,则调用 self.tableView.allowsSelection = NO;
但是如果u仍然想要检测用户触摸u添加 UITapGestureRecognizer
到您的tableView(或tableView.superview)。
U可以更多的控制如果u实现 UIGestureRecognizerDelegate
,这种方式u可以检测,然后选择女巫触摸来接收和巫术不。
要做到这一点,只需添加这个代码到你的 UITableViewController
:
U can handle user touches by adding a UITapGestureRecognizer
to your view.
For example if u don't want to enable row selection in your tableView u call self.tableView.allowsSelection = NO;
But if u still want to detect user touches u add a UITapGestureRecognizer
to your tableView (or to tableView.superview).
U can have more control if u implement the UIGestureRecognizerDelegate
, this way u can detect and then choose witch touches to receive and witch not.
To do that just add this code to your UITableViewController
:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.allowsSelection = NO;
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
tgr.delegate = self;
[self.tableView addGestureRecognizer:tgr]; // or [self.view addGestureRecognizer:tgr];
[tgr release];
}
- (void)viewTapped:(UITapGestureRecognizer *)tgr
{
NSLog(@"view tapped");
// remove keyboard
}
//这是可选的例如在这里我检查用户是否点击了一个textField
// this is optional, it let u choose witch touches to receive, for example here I'm checking if user has tapped on a textField
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view isKindOfClass:[UITextField class]]) {
NSLog(@"User tapped on UITextField");
}
return YES; // do whatever u want here
}
这篇关于UITableView - 外部触摸第一响应者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!