【描述】在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
// Changes the default title of the delete-confirmation button.
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"删你妹";
}
(2) 至于在default delete button上增加背景图片,改变字体大小这些,下次再说,留意博客更新。