UITableViewController(表视图控制器)
UITableViewController继承自UIViewController. 自带了一个tableView, 其根视图就是tableView.创建UIViewVontroller运行之后并不会报错, 会出现两个警告.
我们创建了TableViewController之后会发现有很多被注释掉得代码.
第一个断点警告返回的是分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
第二个断点警告返回的是行高
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
然后被注释掉得方法是创建单元格, 这个在TableView有写
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
这个方法返回的是一个BOOL值, 表示是否允许被编辑, YES是可以, 返回NO是禁止被编辑, 默认为YES.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
这里分别是一个删除和添加的方法, 但是我们在做了添加或删除后, 会发现在刷新之后数据又会回到原来的位置. 是因为这里删除或则添加的只是界面, 所以我们需要写入一下对数据添加和删除的方法.
//一定要先改变数组元素 一定要先改变数组元素 一定要先改变数组元素 重要的事情说三遍
[self.datasource removeObjectAtIndex:indexPath.row];
self.datasource insertObject:@"新数据" atIndex:indexPath.row];
在这里被创建的注释写的很严谨, 先加入数组, 然后再加入到表格中. 我们可以参照的方法写.
在viewDidLoad中, 最下面的一行是一个被注释的一个编辑按钮~! 但是我们在点击了编辑按钮之后会发现只有删除的模式. 所以我们需要为表示图的对应行指定编辑样式,. 样式是个枚举值, 有: Delete, Insert, 和None.
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCellEditingStyleInsert;//添加样式
UITableViewCellEditingStyleDelete;//删除样式
但是很多用过苹果的朋友会问: 不是还有选中么?(一个圆圈, 可以打对勾)
UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;//选择样式
然后是数据的移动:首先我们看这个方法:
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
这个方法返回的BOOL值是说: 是否可以移动, 默认是可以的, 如果想要使某些数据不能移动, 那么我们可以指定某些数据返回NO.
之后就是具体的移动实现.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
将指定的数据移动. 在这里为什么我们不是用exchange 来进行交换呢? 因为移动数据之后, 相当于一个插入操作, 数据移动到指定位置后, 以前的数据会往后进行排列, 改变了index. 所以我们做的是一个插入的操作, 但是单纯的插入的话, 那么以前的数据怎么办? 所以我们是进行了删除, 然后又在指定的位置进行插入.
//1.先获取被移动的数据
id object = [self.datasource [fromIndexPath.row] retain];
//2.将该对象从数组中移除
[self.datasource removeObjectAtIndex:fromIndexPath.row];
//3.将该对象插入到指定下标
[self.datasource insertObject:object atIndex:toIndexPath.row];
//4.释放对象所有权
[object release];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)