UITableView数据编辑
要想对UITableView中的数据进行编辑,需要实现UITableView中的属性和<UITableViewDataSource>和<UITableViewDelegate>协议中的一些方法。
首先需要让UITableView处于编辑状态
在按钮的点击事件中设置点击事件,在点击事件中可以对当前的状态进行判断。
- (void)buttonAction:(id)sender{
if(_table.editing == YES){
[_table setEditing:NO animated:NO];
}else{
[_table setEditing:YES animated:YES];
}
}
UITableView处于编辑状态后就可以对其进行数据编辑。
UITableView数据编辑的一些方法:
1.控制表示图中的哪一行可以进行编辑,其中哪一行可以根据方法中的参数indexPath来进行判断,最后返回为YES或NO来判断哪一行可以进行编辑。(
UITableViewDataSource协议方法)
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
2.控制编辑样式,可以根据indexPath来对其中的行进行控制,然后将编辑样式返回。(UITableViewDelegate协议方法)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
方法的返回值UITableViewCellEditingStyle是编辑数据的样式,它是一个枚举类型的数据。
里面有三种类型:UITableViewCellEditingStyleNone, 没有编辑样式
UITableViewCellEditingStyleDelete, 删除样式
UITableViewCellEditingStyleInsert 添加样式
3.提交删除和添加样式的动作( UITableViewDataSource协议方法)- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
在方法中,可以根据参数editingStyle来判断编辑样式是删除还是添加。删除和添加是对UITableView中的数组进行操作的,所以在移除或添加之后都需要重新刷新数组中的数据,然后重新走协议。
if (editingStyle == UITableViewCellEditingStyleDelete) {//编辑样式是删除
[[_tableArray objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row];// 从数组中将选中的数据移除
} else if(editingStyle == UITableViewCellEditingStyleInsert){//编辑样式是添加
NSMutableDictionary *add = [[NSMutableDictionary alloc] init];
[add setObject:@"1.jpg" forKey:@"image"];
[add setObject:@"吴东阳" forKey:@"name"];
[add setObject:@"男" forKey:@"sex"];
[[_tableArray objectAtIndex:indexPath.section] addObject:add];//将数据添加到数据中
}
[tableView reloadData]; //刷新数据
}
4.上下移动 ,因为要对数据进行操作,所以需要在移动完成后重新刷新数据。(
UITableViewDataSource协议方法)
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;<pre name="code" class="objc">- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
//移动行
NSMutableArray * arr = [_tableArray objectAtIndex:sourceIndexPath.section];
id value = [[arr objectAtIndex:sourceIndexPath.row]retain];//定义一个中间值来保存需要移动的数据
[arr removeObjectAtIndex:sourceIndexPath.row];//从数组中将原来位置的数据移除
[arr insertObject:value atIndex:destinationIndexPath.row];//添加到要移动到的位置
[tableView reloadData];//重新刷新数据
[value release];
}
5.可以对编辑样式中删除字体进行编辑 ,将需要修改的字符串返回即可。(UITableViewDelegate协议方法)
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath;