为了账号安全,请及时绑定邮箱和手机立即绑定

iOS 小知识点 UITableViewCell删除相关

标签:
iOS

####背景:
UITableView的使用
cell上有删除按钮,通过cell上的按钮回调实现删除cell和删除数据源

####问题:
除了第一次删除,或者当前cell的indexpath和相对于tableView的indexpath是一致的情况,删除没有问题。
其他的删除就会出现下面的问题:删除错位,会删除cell上显示的indexPath对应于列表的cell。
例如:cell(0,4)删除,就会删除列表上第五个cell

####原因:
cell的删除回调会在删除时捕获当前cell的indexpath,导致出现删除错位,其实删除的是block捕获的indexpath
tableView就会删除相对于列表的indexPath,而不是当前操作的cell

图片描述

####错误代码展示

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ATableViewCell class]) forIndexPath:indexPath];
    __weak typeof(self) weakSelf = self;
    cell.delegateBlock = ^(UIButton * _Nonnull btn) {
        [weakSelf.datas removeObject:self.datas[indexPath.row]];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    };
    cell.textLabel.text = [NSString stringWithFormat:@"(0,%@)",self.datas[indexPath.row]];
    
    return cell;
}

正确代码展示

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ATableViewCell class]) forIndexPath:indexPath];
    __weak typeof(self) weakSelf = self;
    cell.delegateBlock = ^(UIButton * _Nonnull btn) {
        CGPoint point = [btn convertPoint:btn.bounds.origin toView:tableView];
        NSIndexPath *newIndexPath = [tableView indexPathForRowAtPoint:point];
        [weakSelf.datas removeObject:self.datas[newIndexPath.row]];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationRight];
    };
    cell.textLabel.text = [NSString stringWithFormat:@"(0,%@)",self.datas[indexPath.row]];
    
    return cell;
}
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
32
获赞与收藏
322

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消