如何在自定义的UITableviewCell中检测滑动删除手势?

13
我已经定制了一个UITableViewCell,并想实现“滑动删除”。但我不想要默认的删除按钮,而是想做一些不同的事情。最简单的实现方式是什么?当用户滑动以删除单元格时,是否有一些被调用的方法?我能否防止默认的删除按钮出现?
目前,我认为我必须实现自己的逻辑来避免在UITableViewCell的默认实现中发生的默认删除按钮和缩小动画。
也许我需要使用UIGestureRecognizer吗?
2个回答

16
如果您想要完全不同的操作,请为每个表格视图单元格添加一个 UISwipeGestureRecognizer。
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.


    UISwipeGestureRecognizer* sgr = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellSwiped:)];
    [sgr setDirection:UISwipeGestureRecognizerDirectionRight];
    [cell addGestureRecognizer:sgr];
    [sgr release];

    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
    // ...
    return cell;
}

- (void)cellSwiped:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        UITableViewCell *cell = (UITableViewCell *)gestureRecognizer.view;
        NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
        //..
    }
}

vmanjz的答案更好,因为您不需要为每个表格单元创建UISwipeGestureRecognizer。对于非常大的表格,您可能会看到创建那么多手势识别器时出现严重的滞后。 - Baza207
你可以将手势识别器添加到表视图中。请查看我对类似问题的回答:https://dev59.com/o2445IYBdhLWcg3w_O8m#4604667 - Felix
这种方法的一个问题是它只识别了.Ended状态,而没有.Began状态。 - Zack Shapiro

16

以下是两种可以避免使用删除按钮的方法:

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

谢谢!完美运行! :) - An1Ba7
5
若用户未移除行,则还有方法-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath - Borzh

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