Core Text

Core Text allows strings to be drawn with multiple fonts and styles. It is implemented by the Core Text framework; to utilize it, your app must link to CoreText.framework, and your code must import <CoreText/CoreText.h>. It uses C, not Objective-C, and it’s rather verbose, but getting started with it is not difficult.

A typical simple Core Text drawing operation begins with an attributed string. This is an NSAttributedString (or CFAttributedString; they are toll-free bridged), which is a string accompanied by attributes (such as font, size, and style) applied over ranges. Each attribute is described as a name–value pair. The names of the attributes are listed in Apple’s Core Text String Attributes Reference, along with their value types. The most commonly used attribute is probably kCTFontAttributeName, which determines the font and size of a stretch of text; its value is a CTFontRef, a Core Text type which is not bridged to UIFont. You’ll typically supply attributes as a dictionary of name–value pairs.

For example, imagine that we have a UIView subclass called StyledText, which has a text property that is an attributed string. Its job will be to draw that attributed string into itself:

@interface StyledText : UIView {
}
@property (nonatomic, copy) NSAttributedString* text;
@end

Imagine further that an instance of StyledText appears in the interface and that we have a reference to it as an instance variable called styler. How, then, might we create an NSAttributedString and ...

Get Programming iOS 4 now with O’Reilly online learning.

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