UITableView的编辑: 删除,添加
应用场景:通讯录 中删除联系人,添加联系人
编辑的步骤:
1.开启UITableView的编辑状态
这步需要注意的是一般会在一个按钮里面写, 有开有肯定有关编辑状态,再点一下这个按钮,关闭编辑状态. 我们利用了tableView 的 editing属性(BOOL型)
[self.tableView setEditing:!self.tableView.editing animated:YES];
!self.tableView.editing 对tableView编辑状态取反
并且可以在开启编辑时按钮一个title, 关闭时另一个title
2.允许编辑 返回值是BOOL型 默认是YES
方法: - (BOOL)tableView:(UITableView )tableView canEditRowAtIndexPath:(NSIndexPath )indexPath
这里可以利用indexPath控制哪个分区的哪一行不能编辑
3.指定编辑样式. 主要是删除,添加
方法: - (UITableViewCellEditingStyle)tableView:(UITableView )tableView editingStyleForRowAtIndexPath:(NSIndexPath )indexPath
与第二步一样,利用indexPath控制哪个分区的哪一行的编辑样式
删除:UITableViewCellEditingStyleDelete
添加: UITableViewCellEditingStyleInsert
- 提交编辑
方法: (void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath
根据编辑样式和索引去完成编辑
通讯录为例:
删除时: 1.删除数据
2.判断分区里面已经没数据 没有删除行
3.刷新界面 两种: a.整体刷新 [tableView reloadData]; b.删除自带的刷新方法 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
添加同删除.
移动步骤
1.开启编辑状态
2.允许哪一个分区的哪一行可以移动
3.提交移动 - (void)tableView:(UITableView )tableView moveRowAtIndexPath:(NSIndexPath )sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
1.操作数据源数组 a.把来源索引下数组对应的元素保存一下
b.用来源的索引 删除数组中对应元素
c.插入到移动目的地索引处
d.刷新 [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
4.限制跨区移动 一般情况下我们是只让其同区之间进行移动
- (NSIndexPath )tableView:(UITableView )tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath )sourceIndexPath toProposedIndexPath:(NSIndexPath )proposedDestinationIndexPath
可以判断来源索引与建议目的地索引的section是否相同,相同说明是同区,返回目的地索引,反之返回来源索引