O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required