很多人对于左滑删除cell都不太会,我今天花了点时间看了下这个系统原生的左滑删除cell,很简单,分几步走就可以了。第一步,就是简单的创建列表tableview,然后就是设置
self.tableView.delegate = self;self.tableView.datasource = self;
接下来就是简单的实现代理方法了。
-(NSInteger) numberOfSectionsInTableView:(UITableView)tableView
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
这四个基本方法自不用多说,大家都知道的,接下来就是一些删除要用到的方法。
第一个:
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
其实很多方法看名字就知道可以实现什么,这个方法就是问你可不可以进行编辑,编辑里面包括很多东西,也包括删除这个事件。看返回值是YES还是NO,YES就是可以编辑,反之就是不可以呗,当然,你也可以根据条件判断,哪一行可以编辑,哪一行不可以编辑。第二个:
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
这个就是返回单元格的编辑风格,你是要做什么样的编辑呢,这里只说做删除编辑,所以直接返回return UITableViewCellEditingStyleDelete;就是代表删除的。返回return UITableViewCellEditingStyleInsert;这样的就是插入的。第三个:
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
接下来就是一个比较个性化的设置方法。就是自定义删除按钮的名称,想显示啥就显示啥,差不多就行,return @"删除";像这样就可以了第四个:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (editingStyle == UITableViewCellEditingStyleDelete){ [self.dataArr removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}else{
[self.dataArr addObject:@100];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0];
[tableView insertRowsAtIndexPaths:@[newIndexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}}