2017-09-24 69 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