2.30. Constructing and Displaying Styled Texts


You want to be able to be able to display rich formatted text in your UI components without having to create a separate UI component per attribute. For instance, you may want to display one sentence that contains only one of its words written in bold, inside a UILabel.


Construct an instance of the NSAttributedString or the mutable variant of it, the NSMutableAttributedString, and either set it as the text of a UI component like the UILabel component through its special attributed string property, or simply use the attributed string’s built-in methods to draw the text on a canvas.


Rich text is a thing of legend! A lot of us programmers have had the requirement to display mixed-style strings in one line of text on our UI. For instance, in one line of text you may have to display straight and italic text together, where one word is italic and the rest of the words are regular text. Or you may have had to underline a word inside a sentence. For this, some of us had to use Web Views, but that is not the optimal solution because Web Views are quite slow in rendering their content, and that will definitely impact the performance of your app. In iOS 6, finally, we can start using attributed strings. I don’t know what took Apple so long to introduce this feature to iOS, as Mac developers have been using attributed strings for a long time now!

Before we begin, I want to clearly show you what I mean by attributed strings, ...

Get iOS 6 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.