在UITableView中进行滑动手势时获取单元格的IndexPath

18

我正在UITableView上执行滑动手势,并想知道当前我的手指滑动到了哪个单元格,也就是我从哪个单元格进行了滑动手势。

我需要indexPath,因为我要显示所选单元格的信息。

提前感谢。

3个回答

54

所以你实际上需要做的是从表格中获取滑动手势所在的单元格? 对。你不需要知道 indexPath。首先要这样定义在 tableView 上的滑动操作 -

UISwipeGestureRecognizer *showExtrasSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellSwipe:)];
showExtrasSwipe.direction = UISwipeGestureRecognizerDirectionRight;
[tableView addGestureRecognizer:showExtrasSwipe];
[showExtrasSwipe release];

在实际进行滑动操作之后,您需要对其进行处理。为此,请尝试使用以下代码:

-(void)cellSwipe:(UISwipeGestureRecognizer *)gesture
{
    CGPoint location = [gesture locationInView:tableView];
    NSIndexPath *swipedIndexPath = [tableView indexPathForRowAtPoint:location];
    UITableViewCell *swipedCell  = [tableView cellForRowAtIndexPath:swipedIndexPath];

    //Your own code...
}
所以我们所做的第一件事是先将一个SwipeGestureRecognizer附加到UITableView(而不是UITableViewCell)。然后当在UITableView上发生滑动时,我首先获取在UITableView中手势发生的坐标。接下来,使用这些坐标我可以获取在UITableView中发生滑动的行的IndexPath。最后,使用IndexPath来获取UITableViewCell。很简单吧...
注:我已经被问了太多遍了,所以添加了这个解释,说明为什么我在UITableView上使用了SwipeGestureRecognizer而不是在每个UITableViewCell上使用。
我本可以将SwipeGestureRecognizer附加到每个UITableViewCell上。但我没有这样做,因为我会必须为每个单元格附加单独的SwipeGestureRecognizer。如果我的UITableView中有1000个单元格,那么我将不得不创建1000个SwipeGestureRecognizer对象。这不好。在上述方法中,我只创建了一个SwipeGestureRecognizer,就这样。

2
当然了。这段特定的代码已经见过数百万次的滑动操作! - Srikar Appalaraju
我认为你需要将pinchedIndexPath更改为swipedIndexPath。 - DenTheMan
我在我的表视图中分配了这段代码,它实现了水平表视图样式(表视图内嵌表视图),但是滑动没有触发? didSelectCell 可以正常工作,所以我知道我把代码放在了正确的表中...但是没有成功? - user7865437

0

如果您正在尝试实现“滑动删除”(水平方向滑动),则无需重新发明轮子。只需取消注释UITableViewController委托中的commitEditingStyle:forRowAtIndexPath:方法即可。


-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接