前言
我们在日常开发过程中或多或少都会遇到ios/137955.html">tableview的各种功能,这里简单记录一下tableview的删除和全选删除功能,废话不多说先看一下效果图

既然拿到了需求,就应该想一下如何去实现了,对照上面图片的内容,应该如何实现呢?
看完上图之后发现用到的几个功能:
第一个:左滑删除
第二个:全选删除
左边滑动删除
实现几个代理方法后就可以了
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
return @"删除";
}
改变左滑后按钮的文字
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete;
}
滑动删除样式,有多中可选,这里返回删除样式
- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.dataArray removeObjectAtIndex: indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView reloadData];
}
}
删除点击方法,处理想要删除的数据
这里有一个需要注意点,一定要先更新数据源,在更新UI
左滑删除就这些代码了,是不是很easy,在来看全选的代码
全选删除
这里我用的是全选功能是系统的方法,没有自定义按钮
点击编辑按钮的时候设置tableview
[_tableView setEditing:YES animated:YES];
返回全选的样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}
这样就会出现左侧的选中框
再来就是全选按钮的实现方法
for (int i = 0; i< self.dataArray.count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[_tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
}
if (self.deleteArray.count >0) {
[self.deleteArray removeAllObjects];
}
[self.deleteArray addObjectsFromArray:self.dataArray];
[btn setTitle:@"取消" forState:UIControlStateNormal];










