每当我打电话给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时,将按以下顺序调用委托方法:
numberOfRowsInSection
cellForRowAtIndexPath
didEndDisplayingCell
didEndDisplayingCell
为什么第二次调用这个didEndDisplayingCell
方法?请帮我解决这个问题。
可能的解决方法:
代替
[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])
}
}