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

时间:2011-05-29 12:37:49

标签: iphone ios ipad uitableview gestures

我已经定制了一个UITableViewCell,我想实现“轻扫删除”。但我不想要默认的删除按钮。相反,我想做一些不同的事情。实现这个最简单的方法是什么?当用户滑动删除单元格时,是否有一些方法被调用?我可以阻止默认的删除按钮出现吗?

现在我认为我必须实现我自己的逻辑以避免默认删除按钮并缩小在UITableViewCell的默认实现中滑动删除中发生的动画。

也许我必须使用UIGestureRecognizer?

2 个答案:

答案 0 :(得分:16)

如果您想要做一些完全不同的事情,请将UISwipeGestureRecognizer添加到每个tableview单元格。

// 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];
        //..
    }
}

答案 1 :(得分:14)

以下两种方法可用于避免删除按钮:

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

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