2015-04-20 151 views
1

我想改變我的單元格背景色更改自定義背景色tableViewCell

我看其他的問題,但他們不符合我的情況

我想做一個通知的tableView

例如,如果用戶已經閱讀細胞,細胞的背景顏色將變爲白色

如果不是,顏色爲黃色

在開始

我設置

-(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ 

    if(read[[indexPath row]]) 
    [cell.backView setBckgroundColor:[UIColor whiteColor]; 
    else 
    [cell.backView setBckgroundColor:[UIColor redColor]; 
} 

它的工作原理的顏色,然後我想改變顏色

tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{ 
    read[[indexPath row]] = yes; 
    [cell.backView setBckgroundColor:[UIColor whiteColor]; 
    cell.name.text = @"test"; 
} 

它也能工作

但如果我選擇其他細胞,它改變爲原始顏色

它似乎只能改變一個單元的顏色相同時間

不管我用

cell.backgroundColor 
cell.contentView.backgroundColor 
cell.backView 

它得到相同的結果,誰能幫助我


編輯4/20 20:13

我設置

閱讀
tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath 

對不起方向,我更新代碼

,我選擇其他細胞後,我不叫[重裝的tableView]

,所以我不認爲這是什麼原因

順便說一句,一切都(E 。克標籤)可以改變,但背景顏色

,如果我選擇小區時,它通過導航


答跳轉到其他屏幕

結論第一

tableView: cellForRowAtIndexPath: is well 

tableView: willDisplayCell: is well too 

他們都可以改變背景顏色

但執行時需要制定新的細胞或重裝的tableView

我還是搞不清爲什麼我可以在didselectionRowAtIndexPath 更改標籤,但我不能改變顏色

回答

2

更改顏色使用tableView: willDisplayCell:方法

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (...){ //do your stuff. 
     [cell.backView setBckgroundColor:[UIColor redColor]; 
    } else { 
     [cell.backView setBckgroundColor:[UIColor whiteColor]; 
    } 
} 
0

我想你想設置你的變量

「讀」爲YES

tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

我想你只使用一個變量來記錄狀態,只是因爲你簡化它在這裏發佈,否則你可能想用單獨的變量記錄每個單元格的狀態。

+0

我這樣做,但它不起作用,我再次編輯代碼感謝 – jim

0

您需要更新單元索引處對象的「讀取」屬性。

tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath { 
    [cell.backView setBckgroundColor:[UIColor whiteColor]; 
    currentObjectForThisCell.read = YES; 
} 

則:

-(void)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { 
    if(currentObjectForThisCell.read) 
    [cell.backView setBckgroundColor:[UIColor whiteColor]; 
    else 
    [cell.backView setBckgroundColor:[UIColor redColor]; 
} 
+0

我設置了讀取但它不工作,我再次編輯代碼感謝 – jim

0

在你編輯的代碼,當您選擇單元格,設置讀取標誌YES和改變顏色爲白色,這很好,但在你的cellForRowAtIndexPath:設置單元格的讀標誌YES爲紅色,NO爲白色,這與didSelectRowAtIndexPath:方法中的行爲相反。

+0

對不起,這是我的錯誤,再次編輯 – jim

0

試圖讓選定單元格中的didSelectRowAtIndexPath方法

- (空)的tableView:(UITableView的*)的tableView didSelectRowAtIndexPath方法:(NSIndexPath *)indexPath {

//設置讀取你選擇的指數財產

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
cell.backgroundColor = [UIColor redColor]; 

}

0

你打電話reloadData了的tableView 集合R ead屬性在「didSelectRowAtIndexPath」並重新加載tableView

+0

我在didSelectRowAtIndexPath中設置讀取屬性,但我不重新加載tableView – jim