繁体   English   中英

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

[英]How to detect a swipe-to-delete gesture in a customized UITableviewCell?

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

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

也许我必须使用 UIGestureRecognizer?

如果您想做一些完全不同的事情,请将 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];
        //..
    }
}

这里有两种方法可以用来避免删除按钮:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM