2017-09-24 49 views
0

我試圖在UITableViewCell上的特定indexPath.row處更改單元格的backgroundColor和textLabel。問題是,textLabel正確地在我指定的indexPath.row處進行了更改。然而,當我滾動UITableView時,一些單元格不僅在indexPath.row上更改背景顏色,而且還改變了這些不願意的其他單元格,這些單元格不在我需要的indexPath.row中。cellForRowAtIndexPath在特定索引路徑上執行奇怪的操作

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell* aCell; 
    aCell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];  
    if (indexPath.row == 7) { 
     NSLog(@"enter this specific row"); 
     aCell.textLabel.text = [cellArray objectAtIndex:indexPath.row]; 
     [aCell setBackgroundColor:[UIColor lightGrayColor]]; 
    } 
    return aCell; 
} 

我加了的NSLog上indexPath.row匹配條件,控制檯只能打印出的文本,只要indexPath.row平等的渴望。奇怪的是UITableViewCell更改背景顏色而沒有進入狀態,因爲打印輸出不起作用。 我假設變量aCell無法正常工作跟隨indexPath。我的問題是[aCell setBackgroundColor:[UIColor lightGrayColor]];通過所需的indexPath.row正確工作。

有人可以給我一個建議。非常感謝。

回答

0

想想細胞如何在不同的行中重複使用。你已經改變了這個單元格的顏色永遠。所以當它在不同的行中重用時,它仍然具有改變的顏色。

的解決方案是將單元配置時,這是7排時,這是 7行

if (indexPath.row == 7) { 
    // ... light gray background 
} else { 
    // ... _not_ light gray background! 
} 
+0

它曾作爲您的反饋意見。我仍然無法理解UITableViewCell和indexPath.row的匹配:我假設永遠只改變第7行/單元格的背景顏色,所以只要row = 7就必須改變它。爲什麼其他行!= 7也改變背景。 – ML1426

+0

閱讀我說的話! _細胞被重新使用_。 – matt