iOS TableView 左滑删除方法

刚开始的时候,我还自己在自定义的cell里面加手势,计算偏移量做左滑操作,后来才发现,好蠢啊,出力不讨好。唉。现在分享一下我发现的新方法,都是tableView自带的方法。完全不用在花时间自定义。

第一种。我直接上代码啦~~

//tableView自带的左滑删除

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    //第二组可以左滑删除

    if (indexPath.section == 2) {

        return YES;

    } 

    return NO;

}

// 定义编辑样式

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete;

}

// 进入编辑模式,按下出现的编辑按钮后,进行删除操作

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

    if (editingStyle == UITableViewCellEditingStyleDelete) {


        if (indexPath.section == 2) {

           //这里做删除操作

        }

    }

}

// 修改编辑按钮文字

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {

    return @"删除";

}

这就是第一种方法,直接copy可用,我这里是第二组的cell可以左滑,可以自己更改,也可以更改样式,不止删除一种操作。点击删除 之后的我空在那,自己可以添加代码的。


第二种,直接上代码 哈哈哈

- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {

    //删除

    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {

        [self.titleArr removeObjectAtIndex:indexPath.row];

        completionHandler (YES);

        [self.tableView reloadData];

    }];

    deleteRowAction.image = [UIImage imageNamed:@"删除"];

    deleteRowAction.backgroundColor = [UIColor redColor];


    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];

    return config;

}

这个方法是iOS11之后的方法,可以设置image和title ,还自带动画效果,体验一下吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容