【问题标题】:cellForRowAtIndexPath doing weird action at specific indexpathcellForRowAtIndexPath 在特定的 indexpath 做奇怪的动作
【发布时间】:2017-09-24 14:39:41
【问题描述】:

我尝试在 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 正常工作。

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

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

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

    解决方案是当这是第 7 行时配置单元格both当这是不是第 7 行时。

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

    【讨论】:

    • 它作为您的反馈。我仍然无法理解 UITableViewCell 和 indexPath.row 的匹配:我假设只更改第 7 行/单元格的背景颜色,所以只要 row = 7 就必须更改。为什么其他 row != 7 也更改背景.
    • 看我说的! 单元格被重复使用.
    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多