The title of this blog post should read something like “Hallelujah!” or “It’s about freaking time!” because this feature is long, long, long overdue. Way back in iOS 3.2, Apple allowed the NSAttributedString class to creep into the iOS SDK from the main Mac tool kit. However, none of the UI controls contained any support for rendering these attributed strings.

So, if you wanted to write your own code that read through attributed strings and manually created the various subviews and view configurations necessary for rendering, you were welcome to do so. Of course, this was a colossal pain in the ass and only those people building applications whose sole source of income relied on the use of these things ever tried it.

Now, with iOS6, the pain is gone and we have built-in support for attributed strings. What does that mean? It means that I can create a multi-color piece of text and set it on a label rather than having to create one label for each color like I would normally have done in hackish fashion on previous versions of the SDK.

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:@"ThisIsAttributed"];
[mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,4)];
[mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(5,2)];
[mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(6,10)];

So what does this do? Well, it will produce an attributed string that has the word “This” in red, “is” in blue, and “Attributed” in green.

Instead of setting label text directly the way you’re used to doing with just label.text=@”foo” , now you use a new property called attributedText.

Try it out and enjoy your new freedom. The following are a list of the attributes that come with iOS 6 and attributed strings:

  • NSFontAttributeName – UIFont
  • NSParagraphStyleAttribute – NSParagraphStyle
  • NSForegroundColorAttributeName – UIColor
  • NSBackgroundColorAttributeName – UIColor
  • NSLigatureAttributeName – NSNumber ( 0 -no ligatures, 1 – default ligatures )
  • NSKernAttributeName – NSNumber (0 kerning disabled)
  • NSStrikeThroughStyleAttributeName – NSNumber
  • NSUnderlineStyleAttributeName – NSNumber
  • NSStrokeColorAttributeName – UIColor, default nil
  • NSStrokeWidthAttributeName – NSNumber
  • NSShadowAttributeName – NSShadow, nil default
  • NSVerticalGlyphFormAttributeName – NSNumber , 0 horizontal text, 1 vertical text