OGeek|极客世界-中国程序员成长平台

标题: iOS:在调用 reloadRowsAtIndexPaths 时,didEndDisplayingCell 被调用了两次 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:59
标题: iOS:在调用 reloadRowsAtIndexPaths 时,didEndDisplayingCell 被调用了两次

每当我调用 reloadRowsAtIndexPaths 时; didEndDisplayingCell 方法被调用了两次。为什么会这样?

我已经实现了以下 UITableViewDelegate 和 UITableViewDataSource 的委托(delegate)方法:

我实现 didEndDisplayingCell 的原因是,我想分离 Firebase 监听器。

这是我在里面实现的 didEndDisplayingCell

- (void)tableViewUITableView *)tableView didEndDisplayingCellUITableViewCell *)cell forRowAtIndexPathNSIndexPath*)indexPath{
// detach the listener for the cell at path index indexPath

  CustomCell* customCell = (CustomCell*)(cell);
  [customCell detachListener]; 
}

每当单元格监听更新的数据时,它都会触发 ViewController 中的一个方法,该方法会重新加载 tableViewCell。以下是我实现该方法的方式:

-(void)refreshCellWithIndexPath:(NSIndexPath*) indexPath andData:(CustomData*)data{

  [self.dataArray replaceObjectAtIndex:indexPath.row withObject:data];

  [self.tableView beginUpdates];
  [self.tableView reloadRowsAtIndexPaths[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  [self.tableView endUpdates];
}

此方法执行时,UITableView 的委托(delegate)方法按以下顺序调用:

  1. numberOfRowsInSection
  2. cellForRowAtIndexPath
  3. didEndDisplayingCell
  4. didEndDisplayingCell

为什么第二次调用这个 didEndDisplayingCell 方法?请帮我解决这个问题。



Best Answer-推荐答案


可能的解决方法:

代替

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

使用(迅速):

reloadCounter += 1
CATransaction.begin()
tableView.beginUpdates()
CATransaction.setCompletionBlock {
    self.reloadCounter -= 1
}
tableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: .none)
tableView.endUpdates()
CATransaction.commit()

reloadCounter 是一个 ivar。

在 didEndDisplaying 中:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (reloadCounter == 0) {
        self.output.didEndDisplaying(viewModel: dataProvider.items[indexPath.row])
    }
}

关于iOS:在调用 reloadRowsAtIndexPaths 时,didEndDisplayingCell 被调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44788055/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4