iOS:在调用reloadRowsAtIndexPaths时,会调用didEndDisplayingCell两次

问题描述 投票:2回答:1

每当我打电话给reloadRowsAtIndexPaths; didEndDisplayingCell方法被调用两次。为什么会这样?

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

  • - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  • - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath

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

这是我在didEndDisplayingCell中实现的内容

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)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时,将按以下顺序调用委托方法:

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

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

ios objective-c uitableview firebase firebase-realtime-database
1个回答
0
投票

可能的解决方法:

代替

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

使用(swift):

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是一个伊娃。

并在didEndDisplaying中:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (reloadCounter == 0) {
        self.output.didEndDisplaying(viewModel: dataProvider.items[indexPath.row])
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.