I have a UITableView which makes use of cells with custom backgroundViews. I'm assigning the backgroundViews in tableView:cellForRowAtIndexPath:indexPath:
as suggested here. In a nutshell, dependent upon the position of a UITableViewCell within its UITableView, I want to assign certain backgrou开发者_JAVA百科ndView images. Here's the code in question:
UIImage *rowBackground = nil;
if (row == 0 && row == sectionRows - 1) {
rowBackground = [UIImage imageNamed:@"row_bg_start_and_end.png"];
} else if (row == 0) {
rowBackground = [UIImage imageNamed:@"row_bg_start.png"];
} else if (row == sectionRows - 1) {
rowBackground = [UIImage imageNamed:@"row_bg_end.png"];
} else {
rowBackground = [UIImage imageNamed:@"row_bg.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
This works fine, and I see the results I'm expecting. I have issues, however, when it comes to the removal or addition of rows, which invariably means certain rows retain their previous backgroundViews, rather than recalculating their placement and updating the view in question.
I understand the purpose of dequeueReusableCellWithIdentifier and why this is happening. But I'm not sure how to go about fixing it correctly. I can tell that the rows are recalculated correctly when tableView:cellForRowAtIndexPath:indexPath:
is called by scrolling them off screen, which results in their backgroundView being reset correctly.
Should I be setting the backgroundView property in willDisplayCell:forRowAtIndexPath:
also? How should I handle this situation?
The easiest approach to fix the problem you're having is to reprocess the background images of all visible rows when you add new rows to a section.
i.e.
for (UITableViewCell *cell in aTableView.visibleCells)
{
NSIndexPath *cellIndexPath = [aTableView indexPathForCell:cell];
/* look at the cell.backgroundImage and if it's not appropriate
for the indexPath, update it */
}
You could carefully override all the UITableView methods that insert new rows and only check perform this work for the specific rows that need to be updated but I don't think this would be worth the effort.
精彩评论