数据刷新方法
- 重新刷新屏幕上的所有cell
[self.tableView reloadData];
- 刷新特定行的cell
[self.tableView reloadRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],[NSIndexPath indexPathForRow:1 inSection:0]]
withRowAnimation:UITableViewRowAnimationLeft];
- 插入特定行数的cell
[self.tableView insertRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
- 删除特定行数的cell
[self.tableView deleteRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],[NSIndexPath indexPathForRow:1 inSection:0] ]withRowAnimation:UITableViewRowAnimationLeft];
数据刷新的原则
- cell的个数与模型的个数一定要相等。
- 通过修改模型数据,来修改tableView的展示
- 先修改模型数据
- 再调用数据刷新方法
- 不要直接修改cell上面子控件的属性
数据更新操作
若要处理滑动单元格时单元格的编辑模式需要实现TableView代理方法
1./**
* 只要实现这个方法,左划cell出现删除按钮的功能就有了
* 用户提交了`添加`(点击了添加按钮)\`删除`(点击了删除按钮)操作时会调用
*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) { // 点击了“删除”
// 删除模型
[self.deals removeObjectAtIndex:indexPath.row];
// 刷新表格
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
} else if (editingStyle == UITableViewCellEditingStyleInsert) { // 点击了+
NSLog(@"+++++ %zd", indexPath.row);
}
}
/**
* 这个方法决定了当tableView处于编辑模式时,每一行的编辑类型:insert(+按钮)、delete(-按钮)
*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.row % 2 == 0? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}
2. // 设置tableView的编辑模式
[self.tableView setEditing:YES animated:YES];
//当设置tableView处于编辑模式时,默认情况下cell处于UITableViewCellEditingStyleDelete模式。
UITableView的数据批量操作
- UITableView的默认批处理模式
设置如下:
- (void)viewDidLoad {
[super viewDidLoad];
// 允许在编辑模式进行多选操作 self.tableView.allowsMultipleSelectionDuringEditing = YES;
}
//批量操作点击
- (IBAction)multiOperation:(id)sender {
[self.tableView setEditing:!self.tableView.isEditing animated:YES];
}
//批量删除处理
- (IBAction)remove {
// 获得所有被选中的行
NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
//遍历所有的行号
//注意:数组不可以一边遍历一边做删除操作
NSMutableArray *deletedDeals = [NSMutableArray array];
for (NSIndexPath *path in indexPaths) {
[deletedDeals addObject:self.deals[path.row]];
}
// 删除模型数据
[self.deals removeObjectsInArray:deletedDeals]; // 刷新表格 一定要刷新数据
[self.tableView reloadData];
}