iOS自定义UITableView实现不同系统下的左滑删除功能详解

2020-01-21 07:01:27王冬梅

效果如下所示:

iOS,UITableView,左滑删除
系统自带

虽然这样能基本实现功能,但是我们发现右边的按钮和左边的黄色区域的高度并不一样。这是因为右边按钮是和UITableViewCell的高度一致,而左边的黄色区域只是一张图片而已,其高度设置和UITableViewCell的高度并不一致,才会导致这样的布局出现。如果我们想要删除按钮和左边图片一样的高度,那我们就需要自定义删除按钮的高度了。

二、自定义左滑删除按钮

如果我们想要实现不止一个自定义按钮的功能,那我们就需要在UITableView代理方法- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {}中添加我们所需要的多个按钮了。如下是在不同的cell上添加一个或两个左滑按钮:


//自定义多个左滑菜单选项
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewRowAction *deleteAction;
 deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
 [tableView setEditing:NO animated:YES];//退出编辑模式,隐藏左滑菜单
 }];
 if (indexPath.row == 1) {//在不同的cell上添加不同的按钮
 UITableViewRowAction *shareAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"分享" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
  [tableView setEditing:NO animated:YES];//退出编辑模式,隐藏左滑菜单
 }];
 shareAction.backgroundColor = [UIColor blueColor];
 return @[deleteAction,shareAction];
 }
 return @[deleteAction];
}