iOS – indexPathForRowAtPoint不会以不同的单元格高度返回正确的indexPath

我有包含很多单元格的UITableView。 用户可以通过按下此单元格中的展开button来扩展单元格以查看此单元格中的更多内容(只有一个单元格可以在时间上展开):

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if(selectedRowIndex == indexPath.row) return 205; else return 60; } 

在故事板中,我将UILongPressGesture拖放到单元格button中并将其命名为longPress(单元格是自定义的,它有2个button,1个需要识别LongPressGesture,另一个扩展单元格高度):

 @property (retain, nonatomic) IBOutlet UILongPressGestureRecognizer *longPress; 

而在viewDidLoad中:

 - (void)viewDidLoad { [longPress addTarget:self action:@selector(handleLongPress:)]; } 

这是完美的工作,但是当我使用下面的代码来识别单元格的indexPath,这是错误的,当一个单元格展开:

 - (void)handleLongPress:(UILongPressGestureRecognizer*)sender { // Get index path slidePickerPoint = [sender locationInView:self.tableView]; NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:slidePickerPoint]; // It's wrong when 1 cell is expand and the cell's button I hold is below the expand button } 

任何人都可以请告诉我如何得到正确的indexPath当有不同的细胞高度?
预先感谢

一种方法是将UILongPressGestureRecognizer添加到每个UITableViewCell(都使用相同的select器),然后当调用select器时,可以通过sender.view获取单元格。 也许不是最有效的内存,但如果单个手势识别器在某些情况下不会返回正确的行,这种方式应该工作。

像这样的东西:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; [longPress setMinimumPressDuration:2.0]; [cell addGestureRecognizer:longPress]; [longPress release]; return cell; } 

然后

 - (void)handleLongPress:(UILongPressGestureRecognizer*)sender { UITableViewCell *selectedCell = sender.view; } 

首先将长按手势识别器添加到表格视图中:

 UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; lpgr.minimumPressDuration = 2.0; //seconds lpgr.delegate = self; [self.myTableView addGestureRecognizer:lpgr]; [lpgr release]; 

然后在手势处理程序中:

 -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state == UIGestureRecognizerStateBegan) { CGPoint p = [gestureRecognizer locationInView:self.myTableView]; NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:p]; if (indexPath == nil) NSLog(@"long press on table view but not on a row"); else NSLog(@"long press on table view at row %d", indexPath.row); } } 

您必须小心,以免干扰用户的单元格的正常敲击,并注意在用户举起手指之前handleLongPress可能会触发多次。

谢谢…!