2011-01-20 51 views
1

我有一個UITableView使用自定義backgroundViews單元格。我按照建議heretableView:cellForRowAtIndexPath:indexPath:中分配backgroundViews。簡而言之,依賴UITableView中的UITableViewCell的位置,我想分配一定的backgroundView圖像。這裏是有問題的代碼:UITableViewCell緩存其backgroundView屬性

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; 

這工作正常,我看到我期待的結果。但是,在刪除或添加行時,我遇到了一些問題,這總是意味着某些行保留了以前的backgroundViews,而不是重新計算它們的位置並更新有問題的視圖。

我瞭解dequeueReusableCellWithIdentifier和的用途爲什麼這種情況正在發生。但我不知道如何去正確地修復它。我可以告訴,當tableView:cellForRowAtIndexPath:indexPath:通過在屏幕上滾動來調用時,這些行會被正確地重新計算,這會導致它們的backgroundView被正確重置。

我應該在willDisplayCell:forRowAtIndexPath:中設置backgroundView屬性嗎?我應該如何處理這種情況?

回答

0

解決您遇到的問題的最簡單方法是在將新行添加到節中時,重新處理所有可見行的背景圖像。

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 */ 
} 

你可以仔細重寫插入新行,只檢查需要更新的特定行執行這項工作的所有的UITableView方法,但我不認爲這將是值得的努力。