您的位置:首页 > 其它

TableView实现基本的edit insert delete reorder功能

2016-02-20 00:00 465 查看
摘要: 本文介绍了TableView中关于edit, insert, delete, reorder操作的关键方法

进入编辑TableView编辑模式(右上角的编辑按钮的回调方法)

//edit按钮的回调方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];

if(editing) {
self.editButtonItem.title = @"完成";
}
else {
self.editButtonItem.title = @"编辑";
}
[self.tableView setEditing:editing animated:animated];
}

设置Row左侧的小图标

row的小图标有三种内置的选择: insert,delete,none。

//设置Row左侧的小图标
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row % 2 == 0) {
return UITableViewCellEditingStyleDelete;
}
else{
return UITableViewCellEditingStyleInsert;
}
}

侧滑button的回调方法

在Controller中必须存在该方法才能出现侧滑效果。侧滑button的回调方法用于响应侧滑出现的button。

当点击Row左侧的内置小图标时,同样也会产生侧滑效果。因此,最终中的侧滑逻辑都是在下面的回调方法中实现的。

//该方法是侧滑出来的按钮的回调方法
//并且在Controller中必须存在该方法才能出现侧滑效果
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"response to delete button");
//物理删除
[self.countries removeObjectAtIndex:indexPath.row];

//界面删除
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
else if(editingStyle == UITableViewCellEditingStyleInsert) {
NSLog(@"response to add button");
//物理添加
Country *originalCountry = [self.countries objectAtIndex:indexPath.row];
Country *addCountry = [[Country alloc] initWithName:originalCountry.name];
[self.countries insertObject:addCountry atIndex:indexPath.row];

//界面添加
//为新添加行构造一个indexPath,并放入数组中
NSArray *indexPathArray = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section]];
[self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
}
}

实现Cell Reorder重排功能

为了实现Cell Reorder功能,必须实现下列两个方法。另外,使用Cell Reorder前必须激活编辑模式(右上角的编辑按钮)

//设置哪些row可以做reorder操作
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}

//move操作的回调方法
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {

//物理重排
[self.countries exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];

//重新加载数据
[self.tableView reloadData];
}

Demo

https://git.oschina.net/iSingular/AddDeleteReorderRows.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: