##DAY11 UITableView编辑

2022-11-07,,

##DAY11 UITableView编辑

每一个视图控制器都有一个编辑按钮,因为项目中编辑的应用场景非常多,所以系统预留了一个编辑按钮供我们使用

self.navigationItem.leftBarButtonItem = self.editButtonItem;

添加编辑:

[_tableView setEditing:YES animated:YES];

#pragma mark -------表视图移动操作---------

1、移动的第一步也是需要将表视图的编辑状态打开

setEditing:editing animated:

2、指定哪些行可以移动,默认都可以移动

-------UITableViewDataSource 协议的方法---------

tableView:canMoveRowAtIndexPath:

3、移动完成后要做什么事,怎么完成移动

-------UITableViewDataSource 协议的方法---------

tableView:moveRowAtIndexPath:toIndexPath:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {

//先记录一下原有位置的模型数据

Student *student = _dataArray[sourceIndexPath.row];

//引用计数+1

[student retain];

//删除原位置下的模型数据

[_dataArray removeObjectAtIndex:sourceIndexPath.row];

//在新位置将记录的模型数据添加到数据数组中

[_dataArray insertObject:student atIndex:destinationIndexPath.row];

[student release];

}

#pragma mark -------删除、添加数据---------

1、让将要执行删除、添加操作的表视图处于编辑状态

setEditing:editing animated:

2、指定表视图中哪些行可以处于编辑状态,此方法如果不重写,默认所有的行可以进行编辑

-------UITableViewDataSource 协议的方法---------

tableView:canEditRowAtIndexPath:

3、指定编辑样式,到底是删除还是添加,此方法如果不重写,默认是删除样式,用 | 表示多选

-------UITableViewDelegate 协议的方法---------

tableView:editingStyleForRowAtIndexPath:

4、提交,不管是删除还是提交,这个方法才是核心方法,当点击删除、或者添加按钮时,需要做什么事情,怎样才能完成删除或者添加操作,全部都在这里指定,点击删除按钮或提交按钮触发

-------UITableViewDataSource 协议的方法---------

tableView:commitEditingStyle:forRowAtIndexPath:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

//1、表视图开始更新

[tableView beginUpdates];

//2、判断编辑样式

if(editingStyle == UITableViewCellEditingStyleDelete) {

//3、将该位置下的单元格删除

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

//4、删除数据数组中与该单元格绑定的数据

[_dataArray removeObjectAtIndex:indexPath.row];

}else if (editingStyle == UITableViewCellEditingStyleInsert) {

Student *student = _dataArray[indexPath.row];

//构建一个位置信息

NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];

[tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationTop];

[_dataArray insertObject:student atIndex:index.row];

}

//5、表视图结束更新

[tableView endUpdates];

}

##DAY11 UITableView编辑的相关教程结束。

《##DAY11 UITableView编辑.doc》

下载本文的Word格式文档,以方便收藏与打印。