我在使用“NSForegroundColorAttributeName”更改子字符串颜色时遇到问题。我很困惑,因为正在应用相同子字符串的其他属性(下划线)。
还尝试使用弃用属性“UITextAttributeTextColor”和其他建议属性“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];
答案 0 :(得分:10)
在设置textColor
之后,请确保您没有在UILabel
的attributedText
属性上设置一些颜色。
答案 1 :(得分:7)
问题在于这一行:
NSMutableAttributedString *str = [addActivityLbl.attributedText mutableCopy];
我不知道您的代码的前几行,但可能是addActivityLbl.attributedText
为空的情况。
其次,将NSAttributedString
与UILabel
一起使用并不像使用UITextView
那样可靠。如果未明确提供属性,attributedText
的{{1}}会继承UILabel
text
的属性。
您的UILabel
是黑色的。而你还没有设置addActivityLbl.textColor
。这意味着您的addActivityLbl.attributedText ForegroundColorAttribute
将从addActivityLbl.attributedText
继承BlackColor。
此行不会按预期工作;因为你还没有设置addActivityLbl.textColor
。 addActivityLbl.attributedText
还没有范围。
freeText
由于underlyning不是[str addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:[addActivityLbl.text rangeOfString:freeText]];
的属性(不是由attributionText继承),因此underlyning工作。
我建议您使用addActivityLbl.text
代替(更安全)。另一个选项是在引用某个范围之前设置UITextView
。
答案 2 :(得分:0)