50

Can I set the attributedText property of a UILabel object? I tried the below code:

UILabel *label = [[UILabel alloc] init];
label.attributedText = @"asdf";

But it gives this error:

Property "attributedText" not found on object of type 'UILabel *'

#import <CoreText/CoreText.h> not working

mmd1080
  • 1,812
  • 2
  • 17
  • 29
Shamsiddin Saidov
  • 2,281
  • 4
  • 23
  • 35

8 Answers8

204

Here is a complete example of how to use an attributed text on a label:

NSString *redText = @"red text";
NSString *greenText = @"green text";
NSString *purpleBoldText = @"purple bold text";

NSString *text = [NSString stringWithFormat:@"Here are %@, %@ and %@", 
                  redText,  
                  greenText,  
                  purpleBoldText];

// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:@selector(setAttributedText:)]) {

    // Define general attributes for the entire text
    NSDictionary *attribs = @{
                              NSForegroundColorAttributeName: self.label.textColor,
                              NSFontAttributeName: self.label.font
                              };
    NSMutableAttributedString *attributedText = 
        [[NSMutableAttributedString alloc] initWithString:text
                                               attributes:attribs];

    // Red text attributes
    UIColor *redColor = [UIColor redColor];
    NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:redColor}
                            range:redTextRange];

    // Green text attributes
    UIColor *greenColor = [UIColor greenColor];
    NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:greenColor}
                            range:greenTextRange];

    // Purple and bold text attributes
    UIColor *purpleColor = [UIColor purpleColor];
    UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
    NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:purpleColor,
                                    NSFontAttributeName:boldFont}
                            range:purpleBoldTextRange];

    self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
    self.label.text = text;
}
Michael Kessler
  • 14,245
  • 13
  • 50
  • 64
  • 1
    Bear in mind using rangeOfString like this will cause bugs if some parts of the text are a subset of others. You'd do better to work out ranges yourself using NSRange and working out length of strings manually. – owencm Jul 28 '13 at 18:55
  • @owencm, you are absolutely right. This code can't be used in any situation - especially not when the texts come from the web. This code snippet just demonstrates how to use the attributedText together with backward compatibility... – Michael Kessler Jul 30 '13 at 06:06
  • Good answer. But damn is that an _obtuse_ API. – aroth May 19 '14 at 06:46
  • @aroth , this is the way to do it in code and still support the older OS versions where this functionality is not available. If you support only iOS6+ (most of the apps today) then you may do it in the interface builder - much cleaner... – Michael Kessler May 19 '14 at 08:52
  • this doesn't work when you have same text more than once and apply different attributes .. :( you need to have unique strings. – Ankur Jan 29 '15 at 07:21
  • @Ankur , as I've mentioned in one of the comments above, "This code can't be used in any situation - especially not when the texts come from the web. This code snippet just demonstrates how to use the attributedText together with backward compatibility..." – Michael Kessler Feb 08 '15 at 18:33
33

Unfortunately, UILabel doesn't support attributed strings. You can use OHAttributedLabel instead.

Update: Since iOS6, UILabel does support attributed strings. See UILabel reference or Michael Kessler's answer below for more details.

Chaitanya Gupta
  • 4,043
  • 2
  • 31
  • 41
  • 39
    As of iOS 6, UILabel supports attributed strings via the attributedText property. – Greg Nov 30 '12 at 17:17
12
NSString *str1 = @"Hi Hello, this is plain text in red";

NSString *cardName = @"This is bold text in blue";

NSString *text = [NSString stringWithFormat:@"%@\n%@",str1,cardName];


// Define general attributes for the entire text
NSDictionary *attribs = @{
                          NSForegroundColorAttributeName:[UIColor redColor],
                          NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:12]
                          };
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];


UIFont *boldFont = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
NSRange range = [text rangeOfString:cardName];
[attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor],
                                NSFontAttributeName:boldFont} range:range];


myLabel = [[UILabel alloc] initWithFrame:CGRectZero];

myLabel.attributedText = attributedText;
Zakaria
  • 1,040
  • 3
  • 13
  • 28
Ashish
  • 121
  • 1
  • 2
6

for Swift 4:

iOS 11 and xcode 9.4

  let str = "This is a string which will shortly be modified into AtrributedString"

  var attStr = NSMutableAttributedString.init(string: str)

  attStr.addAttribute(.font,
                value: UIFont.init(name: "AppleSDGothicNeo-Bold", size: 15) ?? "font not found",
                range: NSRange.init(location: 0, length: str.count))

  self.textLabel.attributedText = attStr
Tanvir Nayem
  • 702
  • 10
  • 25
5

For people using swift, here's a one-liner:

myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])
Rob
  • 4,927
  • 12
  • 49
  • 54
3

so,here is the code to have different properties for sub strings ,of a string.

 NSString *str=@"10 people likes this";
    NSString *str2=@"likes this";
    if ([str hasSuffix:str2])
    {
        NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];

    // for string 1 //

        [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,str.length-str2.length)];
         [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0,str.length-str2.length)];
  // for string 2 //

        [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange((str.length-str2.length),str2.length)];
        [string addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:12] range:NSMakeRange((str.length-str2.length),str2.length)];
        label.attributedText=string;
    }
    else
    {
        label.text =str;

    }
bharathi kumar
  • 210
  • 2
  • 8
2

Hope this helps ;)

NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"asdf"];
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attrStr;
Blade
  • 1,435
  • 1
  • 14
  • 22
0
UIFont *font = [UIFont boldSystemFontOfSize:12];
NSDictionary *fontDict = [NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@" v 1.2.55" attributes: fontDict];

UIFont *fontNew = [UIFont boldSystemFontOfSize:17];
NSDictionary *fontDictNew = [NSDictionary dictionaryWithObject: fontNew forKey:NSFontAttributeName];
NSMutableAttributedString *attrStringNew = [[NSMutableAttributedString alloc] initWithString:@“Application” attributes: fontDictNew];
[attrStringNew appendAttributedString: attrString];
self.vsersionLabel.attributedText = attrStringNew;
Vaibhav Shiledar
  • 939
  • 8
  • 15