2013-04-03 21 views
0

我想將我的表格視圖中的第一個單元格的背景顏色設置爲藍色作爲例子,但它不會工作。每次我開始滾動藍色跳轉到不同的單元格。我試過這些代碼。爲單元格分配顏色不工作

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

if([[self.menu objectAtIndex:indexPath.row] isEqual:@"a string"]){ 


    cell.contentView.backgroundColor=[UIColor blueColor] ; 



} 

} 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell  forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

if(indexPath.row==0){ 


    cell.contentView.backgroundColor=[UIColor blueColor] ; 



} 

} 

和我想它也cellfro一行索引路徑。我錯過了什麼?

這是我使用的cellForRowAtIndexPath代碼:

if(indexPath.row==0){ 


    cell.contentView.backgroundColor=[UIColor blueColor] ; 



} 
+0

你錯過了第二部分。您需要一個else語句來涵蓋除if語句之外的其他情況。檢查我的帖子,看看我爲你準備的解決方案。 – Pavan 2013-04-03 22:27:37

回答

0

添加也是別人的,如果...

if(indexPath.row==0){ 


     cell.contentView.backgroundColor=[UIColor blueColor] ; 



    } 
else 
cell.contentView.backgroundColor=[UIColor whiteColor] ; 

的UITableViewCell中的被重用......

-1

在你的情況下,單元格跳轉的顏色,因爲在滾動以保存內存時,tableview中的單元格被重用,以避免發生任何奇怪的事情,您需要專門設置任何單元格的顏色。

你拿到了第一位完成,對顏色的細胞,當indexPath.row == 0現在覆蓋第二部分:

你需要什麼是遵循這樣一個規律:

if(indexPath.row == 0){ 
    //if its the first cell then keep it this color 
    cell.contentView.backgroundColor = [UIColor blueColor]; 
} 
else { 
    //Any other cell keep it this color 
    cell.contentView.backgroundColor = [UIColor whiteColor]; 
} 
+0

爲什麼這會被投票?請在投票時發表評論解釋原因。謝謝 – Pavan 2013-12-27 02:22:47