TableView背景颜色未改变

3

我有一个分组的tableView,现在想将默认背景改成自定义颜色。我已经搜索了很多,最接近的方法是这样的:

- (void)viewDidLoad {
    UIColor *backgroundColor = [UIColor colorWithRed:181 green:293 blue:223 alpha:0];
    self.tableView.backgroundView = [[UIView alloc]initWithFrame:self.tableView.bounds];
    self.tableView.backgroundView.backgroundColor = backgroundColor;
}

这段代码将背景更改为白色,但我无法将其更改为自定义颜色。有人可以帮忙吗?

2个回答

7
您正在错误地创建颜色。RGBA值需要在0.0-1.0范围内。 UIColor将把任何超过1.0的值视为1.0。因此,您的颜色被设置为白色,因为所有三个RGB值都将被视为1.0。还请注意,alpha为0表示完全透明。您希望1.0表示完全可见。
- (void)viewDidLoad {
    UIColor *backgroundColor = [UIColor colorWithRed:181/255.0 green:293/255.0 blue:223/255.0 alpha:1.0];
    self.tableView.backgroundView = [[UIView alloc]initWithFrame:self.tableView.bounds];
    self.tableView.backgroundView.backgroundColor = backgroundColor;
}

请注意,您的绿色值为293。需要将其更改为0到255之间的值。

1
谢谢您的帮助,但是这段代码还没有生效。背景仍然是白色的。 - Chandler De Angelis
Alpha 应该是 1.0,而不是 0.0。 - rmaddy

3

您的RGBA值应该是0.0-1.0。

请确保alpha值不为0.0,以查看颜色效果

UIColor *backgroundColor = [UIColor colorWithRed:0.7 green:1.0 blue:0.85 alpha:1.0];
self.tableView.backgroundView = [[UIView alloc]initWithFrame:self.tableView.bounds];
self.tableView.backgroundView.backgroundColor = backgroundColor;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接