Introduction to Attributed Strings for iOS
Show Apple's description.
Text is an essential part of your application's interface. Get an introduction to the concepts behind manipulating and drawing attributed strings on iOS. Learn how UIKit has adopted attributed strings to make creating text effects even easier.
This is the year
NSAttributedString was introduced:
previously all our UI elements like buttons, textViews etc could only accept attributes for the whole string.
No char no attributes.
If we’re adding a string to an empty
NSMutableAttributedString, this string will have no attributes attached.
If we’re inserting a string to a non-empty
NSMutableAttributedString, the string will inherit the attributes of the char which correspond to the left limit of the insertion range.
The same is true if we’re substituting: each char won’t get the attributes of the char that they replace.
You can replace the characters of an attributed string while preserving the attributes as in the example below:
Note how we need to enumerate the attributes so we have a block call for each range where the attributes change.
If we just replace everything in one shot, as said above, all the characters of the new string will just inherit the attributes of the first char that we’re replacing.
We have paragraph styles! See example below (the !!! symbol is not part of the label):
To do this we need a
setFirstLineHeadIndent and then add the
NSMutableParagraphStyle to our attributed string as an attribute.
This is the paragraph styles list (as of WWDC 2012):
If we assign an attributedString to a
UILabel, then we can still use the
lineBreakMode etc, but bare in mind that those change will change the whole string (the rest of the attributes will remain unchanged).