iOS 使用自定义按钮删除对应cell

ゞ 浴缸里的玫瑰 2022-05-30 05:35 303阅读 0赞

很多app设计的时候因为各种原因,导致tableView不能通过右滑cell的菜单来删除相应的cell。这种情况下删除按钮通常放在对应的自定义cell上,如下图:

之前我的删除功能都是通过 删除数据源对应元素,然后通过tableView reloadData 来实现删除功能。这样做有两个小问题:

1.每删除一个都需要reloadData,感觉很浪费

2.没有删除的动画效果,体验不好

于是按照自己的想法改动了一番,效果如下:

70

以下是实现方法:

自定义的cell通过block将自己传给控制器(这里必须要获得cell的引用,因为删除第一次后

cellForRowAtIndexPath代理方法中的indexPath可能会错误,需要通过cell获取准确的indexPath)

在block中执行deleteRowsAtIndexPaths方法,其中传入的是当前cell的indexPath

beginUpdates和endUpdates最好加上,可以让动画效果更佳同步和顺滑(苹果说的)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

  1. MyTableViewCell \* cell = \[tableView dequeueReusableCellWithIdentifier:@"MyTableViewCell"\];
  2. cell.str = \[self.dataArr objectAtIndex:indexPath.row\];
  3. cell.deleteBlock = ^(UITableViewCell \*currentCell)\{
  4. //获取准确的indexPath
  5. NSIndexPath \*currentIndexPath = \[\_tableView indexPathForCell:currentCell\];

// NSString *value = _dataArr[currentIndexPath.row];

  1. \[self.dataArr removeObjectAtIndex:currentIndexPath.row\];
  2. //beginUpdates和endUpdates中执行insert,delete,select,reload row时,动画效果更加同步和顺滑,否则动画卡顿且table的属性(如row count)可能会失效
  3. \[self.tableView beginUpdates\];
  4. //这里不能直接使用cellForRowAtIndexPath代理方法中传入的indexPath,因为在删除一次后如果继续向下删除,indexPath会因为没有刷新而产生错误
  5. \[self.tableViewdeleteRowsAtIndexPaths:@\[currentIndexPath\]withRowAnimation:UITableViewRowAnimationFade\];
  6. \[self.tableView endUpdates\];
  7. \};
  8. return cell;

}

发表评论

表情:
评论列表 (有 0 条评论,303人围观)

还没有评论,来说两句吧...

相关阅读