66

我想更改 UILabel 文本颜色,但我无法更改颜色,这就是我的代码的样子。

UILabel *categoryTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 46, 16)];
categoryTitle.text = @"abc";
categoryTitle.backgroundColor = [UIColor clearColor];
categoryTitle.font = [UIFont systemFontOfSize:12];
categoryTitle.textAlignment = UITextAlignmentCenter;
categoryTitle.adjustsFontSizeToFitWidth = YES;
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];
[self.view addSubview:categoryTitle];
[categoryTitle release];

标签文本颜色是白色,不是我的自定义颜色。

感谢您的帮助。

4

6 回答 6

177

UIColor 的 RGB 分量在 0 和 1 之间缩放,最高不超过 255。

尝试

categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];

在斯威夫特:

categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)
于 2010-03-28T09:21:53.620 回答
8

可能是更好的方法是

UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];

因此我们有彩色文本

于 2013-06-01T12:25:37.900 回答
2

试试这个,其中 alpha 是不透明度,其他的是红色、绿色、蓝色 chanels-

self.statusTextLabel.textColor = [UIColor colorWithRed:(233/255.f) green:(138/255.f) blue:(36/255.f) alpha:1];
于 2015-05-18T14:26:31.370 回答
1

有可能,它们在 InterfaceBuilder 中没有连接。

文字颜色(colorWithRed:(188/255) green:(149/255) blue:(88/255))正确,可能是连接错误,

backgroundcolor 用于标签的背景颜色,textcolor 用于属性 textcolor。

于 2014-07-03T06:45:57.127 回答
0

在 swift 代码中添加属性文本颜色。

斯威夫特 4:

  let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
  let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];

  let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
  label.attributedText = attributedString

对于斯威夫特 3:

  let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
  let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];


  let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
  label.attributedText = attributedString 
于 2018-07-05T08:56:45.233 回答
0
// This is wrong 
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];

// This should be  
categoryTitle.textColor = [UIColor colorWithRed:188/255 green:149/255 blue:88/255 alpha:1.0];

// In the documentation, the limit of the parameters are mentioned.

colorWithRed:green:blue:alpha: 文档链接

于 2018-07-05T09:06:53.467 回答