我有 UIViewController
和 UITableView
作为 View 中的子项,
我想要做的是,当我触摸任何行时,我会在底部显示一个 View 。如果用户触摸行或底部 View 之外的任何其他位置,我想隐藏该 View 。
问题是当我单击 UITableView
时,它不会触发 touchesEnded
事件。
现在如何检测 UITableView
上的触摸并将其与行选择事件区分开。
谢谢。
最佳答案
无需子类化任何内容,您可以将 UITapGestureRecognizer
添加到 UITableView
并根据您的标准吸收或不吸收手势。
在你看来DidLoad:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapOnTableView:)];
[self.myTableView addGestureRecognizer:tap];
然后,针对条件实现如下操作:
-(void) didTapOnTableView:(UIGestureRecognizer*) recognizer {
CGPoint tapLocation = [recognizer locationInView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:tapLocation];
if (indexPath) { //we are in a tableview cell, let the gesture be handled by the view
recognizer.cancelsTouchesInView = NO;
} else { // anywhere else, do what is needed for your case
[self.navigationController popViewControllerAnimated:YES];
}
}
<小时/>
请注意,如果您只想简单地拾取表格上任意位置的点击,而不是单元格行中的任何按钮的点击,则只需使用上面的第一个代码片段。一个典型的例子是当你有一个 UITableView 并且还有一个 UISearchBar 时。您希望当用户单击、滚动 TableView 等时消除搜索栏。代码示例...
-(void)viewDidLoad {
[super viewDidLoad];
etc ...
[self _prepareTable];
}
-(void)_prepareTable {
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.allowsSelection = NO;
etc...
UITapGestureRecognizer *anyTouch =
[[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(tableTap)];
[self.tableView addGestureRecognizer:anyTouch];
}
// Always drop the keyboard when the user taps on the table:
// This will correctly NOT affect any buttons in cell rows:
-(void)tableTap {
[self.searchBar resignFirstResponder];
}
// You probably also want to drop the keyboard when the user is
// scrolling around looking at the table. If so:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
[self.searchBar resignFirstResponder];
}
// Finally you may or may not want to drop the keyboard when
// a button in one cell row is clicked. If so:
-(void)clickedSomeCellButton... {
[self.searchBar resignFirstResponder];
...
}
希望它对某人有帮助。
关于iphone - UITableView 上的触摸事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5848221/