iOS 使用自定义按钮删除对应cell

很多app设计的时候因为各种原因,导致tableView不能通过右滑cell的菜单来删除相应的cell。这种情况下删除按钮通常放在对应的自定义cell上,如下图:


之前我的删除功能都是通过 删除数据源对应元素,然后通过tableView reloadData 来实现删除功能。这样做有两个小问题:

1.每删除一个都需要reloadData,感觉很浪费

2.没有删除的动画效果,体验不好


于是按照自己的想法改动了一番,效果如下:

iOS 使用自定义按钮删除对应cell


以下是实现方法:

自定义的cell通过block将自己传给控制器(这里必须要获得cell的引用,因为删除第一次后

cellForRowAtIndexPath代理方法中的indexPath可能会错误,需要通过cell获取准确的indexPath


在block中执行deleteRowsAtIndexPaths方法,其中传入的是当前cell的indexPath


beginUpdates和endUpdates最好加上,可以让动画效果更佳同步和顺滑(苹果说的)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    MyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell"];

    cell.str = [self.dataArr objectAtIndex:indexPath.row];

    cell.deleteBlock = ^(UITableViewCell *currentCell){

        //获取准确的indexPath

        NSIndexPath *currentIndexPath = [_tableView indexPathForCell:currentCell];

//        NSString *value = _dataArr[currentIndexPath.row];

        

        [self.dataArr removeObjectAtIndex:currentIndexPath.row];

        //beginUpdates和endUpdates中执行insert,delete,select,reload row时,动画效果更加同步和顺滑,否则动画卡顿且table的属性(如row count)可能会失效

        [self.tableView beginUpdates];

        //这里不能直接使用cellForRowAtIndexPath代理方法中传入的indexPath,因为在删除一次后如果继续向下删除,indexPath会因为没有刷新而产生错误

        [self.tableView deleteRowsAtIndexPaths:@[currentIndexPath] withRowAnimation:UITableViewRowAnimationFade];

        [self.tableView endUpdates];


    };

    return cell;

}