2011-12-02 50 views
0

我有一個變量會記錄需要着色多少個單元格。所以如果這個變量是3,那麼前三個單元格backgroundcolor將會改變。我怎樣才能做到這一點?如何動態更改UITableViewCell的背景顏色?

我知道我需要在

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

更新,但我怎麼能保證頂部細胞具有基於我的變量不同的背景顏色?

回答

2

indexPath參數是您的出發點。如果coloredCells是包含您所着色單元的數量的整數,你的方法將包括像

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { 
    // fetch or create the cell, first 
    UITableViewCell *cell = // ... 

    // then set it up 
    if(indexPath.row < self.coloredCells) { 
     cell.contentView.backgroundColor = [UIColor redColor]; 
    } else { 
     cell.contentView.backgroundColor = [UIColor whiteColor]; 
    } 

    // perform rest of cell setup 
    // ... 

    return cell; 
} 

現在,如果你調整的coloredCells的價值,你需要告知表視圖,一些它的觀點已經改變。做到這一點的最懶的辦法是重新加載整個表:

// elsewhere... 
self.coloredCells = 4; 
[self.tableView reloadData]; 

或者你可以再努力一點重裝只是有彩色背景的細胞:

self.coloredCells = newColoredCount; 
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:newColoredCount]; 
for(int i = 0; i < newColoredCount; i++) { 
    [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]]; 
} 
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone]; 
0

您將測試行號並相應地更改顏色。在使用的cellForRowAtIndexPath:

//having allocated or recycled a cell into myCell pointer above 
//test for row and assign background color like so 

if (indexPath.row < 3) { 
    myCell.contentView.backgroundColor = [UIColor greenColor]; 
} else { 
    myCell.contentView.backgroundColor = [UIColor redColor]; 
} 

//continue configuring your cell 
0

可以使用的tableView:willDisplayCell:forRowAtIndexPath:你UITableViewDelegate的改變,如細胞的背景顏色的東西。實際顯示單元格之前,cellForRowAtIndexPath中所做的更改可能會丟失,因此通常在此方法中執行更好。

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if(indexPath.row < numberOfColoredRows) { 
     cell.backgroundColor = [UIColor redColor]; 
    } 
} 

從這個方法的在參考的討論:

表視圖將此消息發送到其委託它使用 細胞繪製一排,從而允許委託定製之前在顯示之前顯示單元對象 。此方法爲委託人提供了一個 機會來覆蓋表 視圖之前設置的基於狀態的屬性,例如選擇和背景顏色。在代表 返回後,表視圖僅設置alpha和frame屬性,然後僅在行滑入或滑出時爲其設置動畫。

0

不,你不」不得不更新tableView:cellForRowRowAtIndexPath:委託方法。所有你需要做的是這樣的:

[self.tableView cellForRowAtIndexPath:indexPath].backgroundColor = desiredUIColor; 

注意,從id<UITableViewDataSource>類型的主叫tableView:cellForRowAtIndexPath:是從UITableView類型的主叫cellForRowAtIndexPath:不同。前者調用委託方法(不應直接調用該方法),後者返回當前單元格的索引路徑而不重新計算單元格

如果在表格視圖中只有一個部分,計算頂部n單元格的算法很容易。如果你的「變量是要跟蹤多少個單體電池需要花」是(NSUInteger)numberOfHighlightedCells,這是一些簡單的循環代碼你可以運行:

NSUInteger i; 

for (i = 0; i < numberOfHighlightedCells; i++) { 
    [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]].backgroundColor = desiredUIColor; 
} 

但是,如果你有一個以上的部分你表,可能需要一些非常複雜的索引路徑計算。