NSForegroundColorAttributeName不适用于UILabel

Mis*_*sha 6 objective-c nsattributedstring core-text ios

我在使用"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];
Run Code Online (Sandbox Code Playgroud)

nem*_*sis 10

确保你不设置一些颜色textColor的属性UILabel 后,您所设置的attributedText.


ant*_*nio 8

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

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

其次,使用NSAttributedStringwith UILabel并不像使用它那样可靠UITextView.在attributedText一个UILabel不继承从属性textUILabel,如果没有明确提供的属性.

addActivityLbl.textColor是黑人.你仍然没有设置你的addActivityLbl.attributedText ForegroundColorAttribute.这意味着你的addActivityLbl.attributedText遗嘱将继承你的BlackColor addActivityLbl.textColor.

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

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

由于underlyning不是addActivityLbl.text(不是由attributionText继承)的属性,因此underlyning工作.

我建议你UITextView改用(更安全).另一个选择是label.attributedText在引用某个范围之前设置您的.