1.编辑模式:
UITableViewController有一个isEditing属性,用来获取编辑状态,setEditing:animated:方法用来设置是否编辑,当为编辑状态时就会显示编辑操作按钮包括删除,插入,移动等。
2.增加行
UITableView有自带的方案,但这里只说自定义的,先在数据中加入一个新的数据,然后再调用reloadData方法。
- (IBAction)addNewPossession:(id)sender {
//增加一个数据
[[PossessionStore defaultStore] creatPossession];
//重新加载tableView包括询问有多少个section,每个section有多少row,反正回到最开始重新显示tableView
[[self tableView] reloadData];
}
在第一次载入UITableView对象时,该对象会向数据源查询所需要显示的UITableViewCell对象,除此之外还有以下三种情况会出发这种询问。
1.用户滚动表格时。
2.表格移出视图层次结构,然后又加回到视图层次结构时。
3.表格收到reloadData消息时。
3.删除行
1.因为重新显示的时候会询问数据源(DataSource),所以数据源需要在数据中做相应的删除动作。
2.当点击Delete按钮时,UITableView会先调用- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath (NSIndexPath *)indexPath问是否删除,当UITableView发出删除确认deleteRowsAtIndexPaths: withRowAnimation:时才会删除。
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
PossessionStore *pestore = [PossessionStore defaultStore];
NSArray *possessions = [pestore allPossessions];
Possession *p = [possessions objectAtIndex:[indexPath row]];
[pestore removePossession:p];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
}
4.移动行
移动行却不需要发送确认是否移动,只需实现- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath方法,但是同样的要在数据中做相应的操作。
- (void)movePossessionAtIndex:(int)from toIndex:(int)to {
if (from == to) {
return;
}
Possession *p = [allPossessions objectAtIndex:from];
//因为接下来要沫remove,所以这里要retain,开始为1,retain后retain count = 2
[p retain];
//移除from那个
[allPossessions removeObjectAtIndex:from];
//插入from到to的位置
[allPossessions insertObject:p atIndex:to];
[p release];
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
[[PossessionStore defaultStore] movePossessionAtIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
}
当你实现了- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 方法时,若为编辑状态则会显示移动按钮(三个横线),UITableView对象会在运行时向数据源查询是否实现了这个方法,如果实现了则显示相应的按钮。当你点击移动按钮移动整个cell,应该在停下来的时候调用上述方法,然后再调用reloadData方法。