【iPhone】Swipe to delete in a table view cell

何高歌
2023-12-01

【描述】在table view中增加swipe to delete,以实现在cell上向右扫动,显示delete按钮(系统默认,default delete button),向左扫动隐藏delete按钮。点击delete按钮,删除相应的行。


【分析】可能有人会以为,需要在table view上增加UISwipeGestureRecognizer来实现左右滑动的检测(实际上,你也可以这么做,尤其是当自己定义delete按钮时),实际上没有那么复杂,UITableView已经帮我们实现好了。我们仅仅是需要实现以下几个delegate方法就可以了。


(1) - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

(2) - ( UITableViewCellEditingStyle)tableView:( UITableView *)tableView editingStyleForRowAtIndexPath:( NSIndexPath *)indexPath

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


实现函数如下:

// Asks the data source to verify that the given row is editable.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}


// Asks the delegate for the editing style of a row at a particular location in a table view.

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return UITableViewCellEditingStyleDelete;

}


// Asks the data source to commit the insertion or deletion of a specified row in the receiver.

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

{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Remove the cell

        

        // Update the model - do this before update block.

        [_dataSource removeObjectAtIndex:indexPath.row];

        

        [tableView beginUpdates];

        NSArray *array = [NSArray arrayWithObjects:indexPath, nil];

        [tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];

        [tableView endUpdates];

    }   

}


从官方文档中我们可以了解到:

(1) - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

If this method is not implemented, all rows are assumed to be editable. 

(2) - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

If the delegate does not implement this method and the UITableViewCell object is editable (that is, it has its editing property set to YES), the cell has the UITableViewCellEditingStyleDelete style set for it.

所以,实际上,如果仅仅实现swipe to delete in cell的话,那么这两个方法也是没有必要去实现的。但作者还是建议读者在实现这个功能的时候实现这两个delegate方法。

【更多】default delete button的title默认是“delete”,假如我想自定义default delete button的title呢?另外,如果我想给default delete button增加背景图片,或者改变title字体大小呢?
(1) 改变default delete button的话,可以通过实现下面这个delegate方法来实现:

// Changes the default title of the delete-confirmation button.

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return @"删你妹";

}


(2) 至于在default delete button上增加背景图片,改变字体大小这些,下次再说,留意博客更新。







 类似资料: