ios - 仅针对 1 个 tableViewCell 项目的颜色更改每 10 个项目复制一次

标签 ios uitableview

我希望 tableView 的第一项的颜色与列表的其余部分不同。

所以我:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{

    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [_content objectAtIndex:indexPath.row];

    if (indexPath.row==0){
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0.6 alpha:1];
    }
        return cell;
}
  • 并且发生了奇怪的现象。列表中的 10 个项目之后,该项目的颜色也发生了变化。认为可能是“0”重复出现。所以我尝试了:

    if ([cell.textLabel.text isEqualToString:@"我的第一个项目的标题"]){ cell.textLabel.textColor = [UIColor colorWithRed:0 绿色:0 蓝色:0.6 alpha:1]; }

  • 好吧,10 个项目之后,仍在更改该项目的颜色。有什么想法吗?

最佳答案

UITableView 不会为每一行分配一个新单元格。相反,为了节省内存,您可以调用 dequeueReusableCellWithIdentifier:,它会获取之前已分配的单元格。我怀疑正在发生的情况是,您的屏幕可以容纳 10 个单元格,因此当您的第一个单元格滚动到屏幕外时,它会重新用于单元格 11,但其文本颜色保持不变。要解决此问题,只需在颜色分配中添加 else 语句即可。

if (indexPath.row==0){
    cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0.6 alpha:1];
}
else {
    cell.textLabel.textColor = [UIColor someOtherColor];
}

这样,当第一个单元格被重用时,它的颜色将被重置。

关于ios - 仅针对 1 个 tableViewCell 项目的颜色更改每 10 个项目复制一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20587398/

相关文章:

ios - Swift 中的核心数据通知

ios - NSCalendarIdentifierRepublicOfChina vs NSCalendarIdentifierChinese?

ios - 具有动态高度 iOS 的 UITableViewCell

ios - ios中的可扩展 ListView 滚动

ios - 如何检查 TableView 单元格字幕是否彼此相等 iOS

ios - 未找到自动链接框架

iphone - 禁用 tableHeaderView(不要与节标题混淆)滚动

ios - 如何在点击时更改 UITableViewCell 的高度?

ios - UITableView 在 UITableViewCell 内部使用 swift

ios - 我们可以在某个时间或事件后更改通知的内容吗?