【发布时间】:2019-12-30 19:03:28
【问题描述】:
如何为 UITableView 中的单元格设置不同的背景颜色 (特别是七格的彩虹色)
【问题讨论】:
标签: iphone
如何为 UITableView 中的单元格设置不同的背景颜色 (特别是七格的彩虹色)
【问题讨论】:
标签: iphone
设置backgroundColor属性:
cell.backgroundColor = [UIColor redColor];
注意 backgroundColor 必须在tableView:willDisplayCell:forRowAtIndexPath: 方法中设置(来自UITableViewCell reference):
注意:如果要更改 单元格的背景颜色(通过设置 单元格的背景颜色通过 声明的 backgroundColor 属性 UIView) 你必须在 tableView:willDisplayCell:forRowAtIndexPath: 委托的方法而不是在 tableView:cellForRowAtIndexPath: 的 数据源。的变化 a中单元格的背景颜色 组样式表视图有效果 在 iOS 3.0 中不同于 以前版本的操作 系统。它现在影响内部区域 圆角矩形而不是 外面的区域。
使用indexPath参数实现彩虹效果。
【讨论】:
如果您想根据实际单元格数据对象中的某些状态设置单元格颜色,那么这是另一种方法:
如果您将此方法添加到您的表格视图委托中:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = cell.contentView.backgroundColor;
}
然后在你的 cellForRowAtIndexPath 方法中你可以这样做:
if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
这省去了在 willDisplayCell 方法中再次检索数据对象的麻烦。
【讨论】:
不要忘记将 tableView 的背景颜色设置为 clearColor。否则不会显示单元格的clearColor,因为tableView的背景颜色默认为whiteColor。甚至当单元格颜色变为 clearColor 时也会显示 whiteColor,因为 tableView 背景颜色仍然是 whiteColor。记住。
【讨论】:
你可以这样设置:
cell.contentView.backgroundColor = [UIColor colorWithRed:249.0/255 green:237.0/255 blue:224.0/255 alpha:1.0];
【讨论】:
很确定 UITableViewCell 是 UIView 的子类,所以:
cell.backgroundColor = [UIColor blueColor];
对于可怕的彩虹色,这里有一个例子:
static NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], etc..., nil];
cell.backgroundColor = [colors objectAtIndex:indexPath.row];
【讨论】:
试试这个
cell.backgroundVIew.backgroundColor = [UIColor orangeColor];
【讨论】:
如果您将UITableViewCell 子类化,则可以在-layoutSubviews 中可靠地设置self.backgroundColor。至少根据我的经验,这适用于 tableView:willDisplayCell:forRowAtIndexPath: 不适用的奇怪情况。
【讨论】:
您可能会得出结论,“willDisplayCell”仍然无法像我最初那样工作。它最初对我不起作用的原因是因为我没有正确使用颜色。
别忘了使用自定义颜色时需要除以 255.0f:
[UIColor colorWithRed:44/255.0f green:50/255.0f blue:65/255.0f alpha:1];
类似下面的内容会产生一个白色的单元格:
//DON'T DO
[UIColor colorWithRed:44 green:50 blue:65 alpha:1];
当它真正将背景设置为白色时,让它看起来好像什么都没做。
【讨论】: