上次一我们说了UITableView的初始化等一些简单的内容,今天我们来详细看一下TableView里面的很多操作。
首先还是要新建工程,创建一个tableview并显示。(上节课内容)
创建完以后,我们新建一个按钮,用来进行编辑:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"UITableView";
_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.bounds.size.height ) style:UITableViewStylePlain];
[_table setDelegate:self];//遵循uitableview协议
[_table setDataSource:self];//遵循uitableview数据源协议
[self.view addSubview:_table];
[self leftButtonCreated];//创建按钮的方法
}
#pragma mark -
#pragma mark ButtonCreated
- (void)leftButtonCreated{
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"edit" style:UIBarButtonItemStyleBordered target:self action:@selector(leftButtonClicked)];
}
- (void)leftButtonClicked{
[_table setEditing:![_table isEditing] animated:YES];//设置按钮点击状态
}
然后我们来实现一下一个方法:
1.设置tableViewcell是否可以移动:
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
2.tableViewCell移动的具体实现:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
[_arr insertObject:[_arr objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row + 1];
[_arr removeObjectAtIndex:sourceIndexPath.row];
[_table reloadData];
}
这里的sourceIndexPath是要移动的cell的位置,destinationIndexPath是需要移动到的位置。
创建完以上两个方法以后,我们就可以来移动cell了:
移动之前的tableView;
我们将1移动到2的下面,移动之后的tableview:
下面我们来进行tableviewCell的添加和删除,首先要实现以下几个方法:
1.设置tableView是否可以编辑:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
2.设置tableView的编辑样式:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
// return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;//编辑样式会变成多选的情况
if (indexPath.row == 0) {
return UITableViewCellEditingStyleInsert;//样式变成添加
}
return UITableViewCellEditingStyleDelete;//样式编程删除
}
我假设第一个成员是添加样式,其他的都是删除样式。
3.根据样式来进行具体的操作:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_arr removeObjectAtIndex:indexPath.row];
}else if (editingStyle == UITableViewCellEditingStyleInsert){
[_arr insertObject:@"hello" atIndex:indexPath.row + 1];
}
[tableView reloadData];//tableView重新加载数据
}
我们运行一下:
我添加了一个名字为hello 的cell,然后将名字为3的cell删除。
这样就可以实现tableView的添加和删除操作了。
对与tableView 的操作,主要是实现tableViewDlegete里面的方法,有兴趣的话大家可以自己实现一下。
欢迎留言批评指正,谢谢。