Using NSAttributedString


As per the Apple Documentation, an NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.

In short, an NSAttributedString allows you to apply styles on the text. As of the latest iOS sdk (8.0), you can apply the following attributes to an NSString object.

  • NSFontAttributeName
  • NSParagraphStyleAttributeName
  • NSForegroundColorAttributeName
  • NSBackgroundColorAttributeName
  • NSLigatureAttributeName
  • NSKernAttributeName
  • NSStrikethroughStyleAttributeName
  • NSUnderlineStyleAttributeName
  • NSStrokeColorAttributeName
  • NSStrokeWidthAttributeName
  • NSShadowAttributeName
  • NSTextEffectAttributeName
  • NSAttachmentAttributeName
  • NSLinkAttributeName
  • NSBaselineOffsetAttributeName
  • NSUnderlineColorAttributeName
  • NSStrikethroughColorAttributeName
  • NSObliquenessAttributeName
  • NSExpansionAttributeName
  • NSWritingDirectionAttributeName
  • NSVerticalGlyphFormAttributeName

Lets look at the most used attributes :  

NSFontAttributeName

NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Italic" size:30.0] };

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Italic Text" attributes:attributes];

self.attributedLabel.attributedText = attributedString;

Output : Italic Text

NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] };

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Bold Text" attributes:attributes];

self.attributedLabel.attributedText = attributedString;

Output : Bold Text

 

NSForegroundColorAttributeName

NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor blueColor] };

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Blue Text" attributes:attributes];

self.attributedLabel.attributedText = attributedString;

Output : I am blue colored

 

NSUnderlineStyleAttributeName

NSDictionary *attributes = @{ NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Underlined Text" attributes:attributes];

self.label.attributedText = attributedString;

Output : Underlined Text

You can put fontName of your choice for creating attributed NSStrings