TableView实现基本的edit insert delete reorder功能
2016-02-20 00:00
465 查看
摘要: 本文介绍了TableView中关于edit, insert, delete, reorder操作的关键方法
当点击Row左侧的内置小图标时,同样也会产生侧滑效果。因此,最终中的侧滑逻辑都是在下面的回调方法中实现的。
进入编辑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相关文章推荐
- 理解Cell的注册与重用机制
- 4个理由告诉你Java为何排行第一
- Python中的数据结构和面向对象设计模式的算法
- python 读书笔记(1)
- wiki
- 【前端开发者福利】html5移动端常见问题集锦
- cobar 之外的选择 ReplicationDriver
- RabbitMQ的几种典型使用场景
- Java 正则表达式
- linux内核目录结构
- 处理 CentOS/Linux GLIBCXX_3.4.15 not found error
- 运行locate无法找到mlocate.db的解决方法
- 关于 SSRS 的使用
- ContentProvider:读取手机通讯录、号码等信息(16)
- CentOS7下安装和使用Xdebug
- centos7安装telnet服务
- 极光推送
- JS中创建对象
- Spring 导出压缩文件
- ps cc 2014 智能切图