2014-07-13 21 views
0

聲明:我在iOS 8上,所以有機會這是一個錯誤。cellForRowAtIndexPath屬性更改更改多個單元格

我試圖以編程方式編輯特定事件後特定索引在UITableView中的單元格的backgroundColor。我使用下面的代碼:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
cell.backgroundColor = [UIColor colorWithRed:1 green:0.84 blue:0 alpha:1]; 

雖然這工作得很好,只要我滾動,我看到其他單元格與改變背景顏色。我認爲它是與下面的代碼在我- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法:

static NSString *simpleTableIdentifier = @"SimpleTableCell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
... 

我懷疑,因爲所有的細胞都帶有這個標識產生的,莫名其妙的性能感到困惑(雖然風格不那麼適用於一切,只有隨機單元格,所以這是違背這一理論的)。謝謝您的幫助!

+0

你應該永遠不會改變的cellForRowAtIndexPath之外的單元格的內容。細胞在從視圖中滾動出來並回到視圖中時被「回收」,並且在該方法中未做出的任何更改將在滾動時蒸發。 –

回答

1

您需要更改所有單元格的背景。

if (/* some condition for special background color */) { 
    cell.backgroundColor = ... // special background color 
} else { 
    cell.backgroundColor = ... // normal background color 
} 

這可以避免重複使用問題。對於您希望爲某些單元格設置不同的單元屬性,您必須遵循此模式。

+0

我假設你的意思是在'tableView ... cellForRowAtIndexPath ...'方法中?如果是這樣,那麼每次我想在單個單元格上更改屬性時都需要重新加載tableView,否則不會? **編輯**我想我明白你的意思......所以我應該爲新的單元設置一個默認的背景顏色,而且根據是否發生改變單元顏色的事件來設置背景顏色。我會試試這個...... –

+0

是的,在'cellForRow ...'中。不,這並不意味着您需要重新加載表格視圖。 – rmaddy

+0

@RubenMartinezJr。 - 您使用'reloadRowsAtIndexPaths'來重新加載部分表。 –

0

有一種方法可以像下面那樣更改背景顏色。例如你想改變備用行顏色: -

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (indexPath.row%2== 0) { 
[cell setBackgroundColor:[UIColor yellowColor]]; 
} 
else { 
[cell setBackgroundColor:[UIColor whiteColor]]; 
} 
0

比方說,你想使單元可選和不可選擇的做到這一點:

var selected = [Int:Int]() 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! YourCellTypeClass 

    //check if the cell button is selected 
    if((selected[indexPath.row]) != nil){ 
     cell.backgroundColor = UIColor.blueColor() 
    }else{ 
     cell.backgroundColor = UIColor.whiteColor() 
    } 

    return cell; 
} 

func selectCell(index: Int){ 
    let indexPath = NSIndexPath(forRow: index, inSection: 0) 
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! YourCellTypeClass 

    if((selected[index]) != nil){ 
     cell.backgroundColor = UIColor.blueColor() 
     selected[index] = nil 
     print("unselected: \(index)") 
    }else{ 
     ccell.backgroundColor = UIColor.redColor() 
     selected[index] = index 
     print("selected: \(index)") 
    } 


}