UITableView 方法“indexPathForRowAtPoint:"的奇怪行为 [英] Weird behavior of UITableView method "indexPathForRowAtPoint:"
问题描述
如下面的代码所示,当tableview被拉伸(从不向上滚动)时,NSLog(@"tap is not on the tableview cell")
将始终被调用(因为我认为 indexPath 将始终为零).但是,当我点击部分编号大于 2 的部分标题中的头像时,NSLog
不会被调用.很奇怪,有人知道这是怎么回事吗?
As show in the following code, when the tableview is stretched (never scrolled up), the NSLog(@"tap is not on the tableview cell")
will always be called (as i thought the indexPath will always be nil). But when i tap the avatar in the section header with section number greater than 2, the NSLog
does not get called. It is weird, anyone know what's going on here?
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
...
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 1;
[avatar addGestureRecognizer:tapGesture];
//avatar is UIImageView and the user interaction is enabled.
[headerView addSubview: aMessageAvatar];
return headerView;
...
}
-(void)handleTapGesture:(UITapGestureRecognizer *)sender
{
CGPoint point = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
if (!indexPath) {
NSLog(@"tap is not on the tableview cell");
}
}
推荐答案
您的点击位置是标题中的位置,而不是单元格,因此它永远不会匹配单元格 indexPath
.
Your tap location is the location in the header, not a cell, so it would never match a cell indexPath
.
您可以将 avatar
视图的 tag
设置为 viewForHeaderInSection
中的节号,然后检索 中的节号>handleTapGesture
通过 sender.view.tag
.例如:
You could probably set the tag
for the avatar
view to be the section number in viewForHeaderInSection
and then retrieve the section number in handleTapGesture
via sender.view.tag
. For example:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
...
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 1;
avatar.tag = section; // save the section number in the tag
avatar.userInteractionEnabled = YES; // and make sure to enable touches
[avatar addGestureRecognizer:tapGesture];
//avatar is UIImageView and the user interaction is enabled.
[headerView addSubview: aMessageAvatar];
return headerView;
...
}
-(void)handleTapGesture:(UITapGestureRecognizer *)sender
{
NSInteger section = sender.view.tag;
NSLog(@"In section %d", section);
}
这篇关于UITableView 方法“indexPathForRowAtPoint:"的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!