Last active
January 16, 2020 18:59
-
-
Save kristopherjohnson/f18fb872ace42707c426 to your computer and use it in GitHub Desktop.
Update visible cells from a UITableViewController without calling -[UITableView reloadData]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)reconfigureVisibleCells | |
{ | |
NSInteger sectionCount = [self numberOfSectionsInTableView:self.tableView]; | |
for (NSInteger section = 0; section < sectionCount; ++section) { | |
NSInteger rowCount = [self tableView:self.tableView numberOfRowsInSection:section]; | |
for (NSInteger row = 0; row < rowCount; ++row) { | |
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section]; | |
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; | |
if (cell != nil) { | |
[self configureCell:cell forRowAtIndexPath:indexPath]; | |
} | |
} | |
} | |
} | |
// Cell configuration code, shared by -tableView:cellForRowAtIndexPath: and reconfigureVisibleCells | |
- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
// ... | |
} |
Here's how I do it:
- (void)configureVisibleCellsForTableView:(UITableView *)tableView animated:(BOOL)animated {
[self tableView:tableView configureRowsAtIndexPaths:tableView.indexPathsForVisibleRows animated:animated];
}
- (void)tableView:(UITableView *)tableView configureRowsAtIndexPaths:(NSArray *)indexPaths animated:(BOOL)animated {
for (NSIndexPath *indexPath in indexPaths) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell) {
[self tableView:tableView configureCell:cell forRowAtIndexPath:indexPath animated:animated];
}
}
}
- (void)tableView:(UITableView *)tableView configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated {
// Cell configuration
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about using
UITableView
'sindexPathsForVisibleRows
:I also suggest changing the signature of
-configureCell:forRowAtIndexPath:
to:Then you get:
I also think it's safe to remove
if (visibleCell != nil)
, since we are explicitly asking the table view for the visible rows, but I kept it in case, for some (possibly non-existent) reason, no cell has been allocated for that row.