如何更改某些单词的UILabel文本颜色变化?

时间:2014-10-23 05:23:01

标签: ios objective-c iphone ios7 ios8

说我有UIlabel,我想改变某个单词的文字颜色。例如我的标签文本是 "立即购买并享受50%折扣精选鞋子限时优惠"

我" 50%"和"有限"想改变颜色

如果在标签文本中生成,则预定义一些单词,然后更改颜色。拳头找到然后改变颜色和字体或子字符串。

2 个答案:

答案 0 :(得分:1)

为此,请使用NSAttributedString:

 NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

详细信息:https://github.com/joaoffcosta/UILabel-FormattedText

答案 1 :(得分:0)

您可以使用NSMutableAttributedString

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Shop now and get up 50% off Select shoes Limited time offer"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(, )];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(, )];