Search code examples
iphoneipadnsattributedstring

iphone/ipad: How exactly use NSAttributedString?


Yes, many people are saying about Rich Text in iPhone/iPad and many knows about NSAttributedString.

But how to use NSAttributedString? I searched for much time, no extract clues for this.

I know how to set up a NSAttributedString, then what should I do to display a text on iPhone/iPad with rich text?

The official docs says it should be used with CoreText.Framework, what does that mean?

Is there any simple way like this?

NSAttributedString *str;
.....
UILabel *label;
label.attributedString = str;

Solution

  • You should take a look at AliSoftware's OHAttributedLabel. It is a subclass of UILabel that draws an NSAttributedString and also provides convenience methods for setting the attributes of an NSAttributedString from UIKit classes.

    From the sample provided in the repo:

    #import "NSAttributedString+Attributes.h"
    #import "OHAttributedLabel.h"
    
    /**(1)** Build the NSAttributedString *******/
    NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
    // for those calls we don't specify a range so it affects the whole string
    [attrStr setFont:[UIFont systemFontOfSize:12]];
    [attrStr setTextColor:[UIColor grayColor]];
    // now we only change the color of "Hello"
    [attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
    
    
    /**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
    myAttributedLabel.attributedText = attrStr;
    // Use the "Justified" alignment
    myAttributedLabel.textAlignment = UITextAlignmentJustify;
    // "Hello World!" will be displayed in the label, justified, "Hello" in red and " World!" in gray.
    

    Note: In iOS 6+ you can render attributed strings using the attributedText property of UILabel.