NSForegroundColorAttributeName不适用于UILabel

我有一个问题,使用“NSForegroundColorAttributeName”更改子string的颜色。 我很困惑,因为同一个子string的其他属性被应用(下划线)。

还尝试使用不推荐的属性“UITextAttributeTextColor”和其他build议的属性“kCTForegroundColorAttributeName”,并获得相同的效果。

我正在编译iOS 7。

在这里输入图像说明

NSString *freeText = [NSString stringWithFormat:@"(%@)", self.me.activity.text]; int lblMaxWidth = arrImgView.origin.x - WPRConstraints.BorderOffset; int lblMaxHeight = self.activityView.size.height - WPRConstraints.BorderOffset * 2; RevUILabel *addActivityLbl = [[RevUILabel alloc] initWithFontNameMultiLine:[WPRFonts LattoBold] size:16 sizeConstrain:CGSizeMake(lblMaxWidth,lblMaxHeight)]; addActivityLbl.text = [NSString stringWithFormat:@"%@ %@", Translate(self.me.activity.activityKey), freeText] ; addActivityLbl.textColor = BlackColor; NSMutableAttributedString *str = [addActivityLbl.attributedText mutableCopy]; [str addAttribute:NSUnderlineColorAttributeName value:[UIColor redColor] range:[addActivityLbl.text rangeOfString:freeText]]; [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:1] range:[addActivityLbl.text rangeOfString:freeText]]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[addActivityLbl.text rangeOfString:freeText]]; addActivityLbl.attributedText = str; addActivityLbl.frame = CGRectMake(WPRConstraints.BorderOffset, WPRConstraints.BorderOffset, addActivityLbl.size.width, addActivityLbl.size.height); [self.activityView addSubview:addActivityLbl]; 

问题是这一行:
NSMutableAttributedString *str = [addActivityLbl.attributedText mutableCopy];

我不知道以前的代码行,但可能是addActivityLbl.attributedText为空的情况。

其次,与UILabel一起使用NSAttributedString并不像使用UITextView那样可靠。 如果未明确提供属性,则UILabel的属性text将从UILabeltextinheritance属性。

你的addActivityLbl.textColor是黑色的。 而你还没有设置你的addActivityLbl.attributedText ForegroundColorAttribute 。 这意味着你的addActivityLbl.attributedText将inheritance你的addActivityLbl.textColor

这条线不会按预期工作。 因为你还没有设置你的addActivityLbl.attributedTextfreeText还没有范围。

[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[addActivityLbl.text rangeOfString:freeText]];

因为underlyning不是addActivityLbl.text的属性(不能被attributesTextinheritance)。

我build议你使用UITextView (这是更安全)。 另一个select是设置你的label.attributedText ,然后引用它的某个范围。

确定你没有设置一些颜色在UILabel textColor属性 ,设置的。

我有一个类似的问题,试图设置UIButton的属性标题的颜色。 我正在应用其他属性,如下划线,他们的工作,但NSForegroundColorAttributeName属性是完全没有影响。

把头发拉出来质疑自己的理智后,我终于发现我的问题是在故事板上,我的button被设置为Systembutton:

在这里输入图像说明

它需要是Custom

在这里输入图像说明

改变故事板中的一个设置后,我可以设置NSForegroundColorAttributeName与预期,理智的行为。

我希望这可以帮助别人!