NSForegroundColorAttributeName not working for UILabel

Misha picture Misha · Feb 15, 2015 · Viewed 9.2k times · Source

I have a problem changing substring color using "NSForegroundColorAttributeName". I'm confused since other attributes for the same substring are being applied(underline).

Also tried to use deprecated attribute "UITextAttributeTextColor" and other suggested attribute "kCTForegroundColorAttributeName" and got the same effect.

I'm compiling for iOS 7.

enter image description here

    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];

Answer

nemesis picture nemesis · Sep 28, 2016

Make sure you're not setting some color on textColor property of UILabel after you've set the attributedText.