我希望 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/