cellForRowAtIndexPath在特定的索引路径

时间:2017-09-24 14:39:42

标签: ios objective-c uitableview

我尝试在UITableViewCell上的特定indexPath.row处更改单元格的backgroundColor和textLabel。问题是,textLabel在我指示的indexPath.row上正确更改了。但是,当我滚动UITableView时,一些单元格不仅会在indexPath.row上更改背景颜色,而且还会更改这些不愿意的其他单元格,这些单元格不在我所需的indexPath.row中。

- (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;
}

我在indexPath.row匹配条件上添加了一个NSLog,只要indexPath.row等于欲望,控制台就会打印出文本。奇怪的是UITableViewCell更改背景颜色而没有进入条件,因为打印输出不起作用。 我假设变量aCell无法正常跟随indexPath。 我的问题是如何[aCell setBackgroundColor:[UIColor lightGrayColor]];通过所需的indexPath.row正确工作。

有人可以给我一个建议。非常感谢。

1 个答案:

答案 0 :(得分:0)

考虑如何在不同的行中重用单元格。您已经永久地更改了此单元格的颜色。因此,当它在不同的行中重复使用时,它仍然具有更改的颜色。

解决方案是在第7行时将 配置为 第7行。

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