数据更新
数据更新:添加、删除、更改
批量操作
- 不能设置在cell上,因为循环利用会引发其他问题
批量操作
- 设置打勾控件、给图、默认为隐藏
- 在cell代码中连线
- 在模型中设置变量
- set方法赋值 self.checkVIew.hidden = !deal.checked;
控制器代码中实现下面方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; WZDeal *deal = self.deals[indexPath.row]; // 模型的打钩属性取反 deal.checked = !deal.checked; [tableView reloadData]; }
- (IBAction)remove:(id)sender { // 遍历被打勾的cell,存在可变数组中 NSMutableArray *deleteDeals = [NSMutableArray array]; for (WZDeal *deal in self.deals) { if (deal.isChecked) [deleteDeals addObject:deal]; } // 移除全部打勾的cell [self.deals removeObjectsInArray:deleteDeals]; [self.tableView reloadData]; }
/**
* 只要实现这个方法,左划cell出现删除按钮的功能就有了
* 用户提交了添加(点击了添加按钮)\删除(点击了删除按钮)操作时会调用
*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.deals removeObject:_deals[indexPath.row]];
// 刷新表格
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}else if(editingStyle == UITableViewCellEditingStyleInsert)
{
}
}
/**
* 这个方法决定了编辑模式时,每一行的编辑类型:insert(+按钮)、delete(-按钮)
*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.row % 2 == 0? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}
弹框控件
// 创建弹框控制器
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入团购信息" message:nil preferredStyle:UIAlertControllerStyleAlert];
// 添加按钮
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
// 创建模型
XMGDeal *deal = [[XMGDeal alloc] init];
deal.title = [alert.textFields[0] text];
deal.price = [alert.textFields[1] text];
[self.deals insertObject:deal atIndex:0];
// 刷新数据
[self.tableView reloadData];
}]];
// 添加文本输入框
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"请输入团购名字";
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"请输入团购价格";
}];
// 显示控制器
[self presentViewController:alert animated:YES completion:nil];
- 增加数据,只能更改模型
// 提醒tabelView,模型数据发生了变化,请重新识别,请重新向数据源索要数据
[self.tableView reloadData];
// 插入某些特定的行
[self.tableView insertRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0]
] withRowAnimation:UITableViewRowAnimationLeft];
}
- (IBAction)remove {
// 移除模型数据
[self.deals removeObjectAtIndex:0];
[self.deals removeObjectAtIndex:0];
[self.deals removeObjectAtIndex:0];
// 刷新表格
[self.tableView reloadData];