您的位置:首页 > 产品设计 > UI/UE

UITableView 左滑删除cell

2016-01-26 10:32 423 查看
转载自http://www.jianshu.com/p/36c5fabf3261。

很多人对于左滑删除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];

}

}

这个方法我个人认为应该算是最重要的方法了,无论你的列表里面有没有数据,这个方法你都应该写上,一般的列表上显示的数据都是由数组或者字典里的数据提取出来的,这个方法中你就需要在你提取数据的源头进行删除数据,不然即使及删除了列表的行,也不管用,那条数据还是会显示出来,或者什么地方没弄好,直接是报错,所以要注意这一点。在删除模式中,顺序很重要,稍微出一点错就会崩溃。像我上面写的,要根据所在行删除数组对应的数据,然后是更新界面。下面的那个else里面就是插入操作。

这样就是基本完成了左滑删除的功能。

(要是有哪些地方错了请指正我,我也是初学者,希望与大家共同学习,共同进步)

tableviewcell的左滑删除Demo 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: