Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Created June 23, 2012 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jverkoey/2977410 to your computer and use it in GitHub Desktop.
Save jverkoey/2977410 to your computer and use it in GitHub Desktop.
NIAttributedLabel Example 2
NSString* string =
@"For 20 years she has ventured into the dark horizon. "
@"At long last, a planet grows in the distance. "
@"\"Hello world!\" she exclaims.";
// We're going to customize the words "hello" and "world" in the string above to make them stand
// out in our text.
NSRange rangeOfHello = [string rangeOfString:@"Hello"];
NSRange rangeOfWorld = [string rangeOfString:@"world!"];
// We must create a mutable attributed string in order to set the CoreText properties.
NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithString:string];
// See http://iosfonts.com/ for a list of all fonts supported out of the box on iOS.
UIFont* font = [UIFont fontWithName:@"Futura-MediumItalic" size:30];
// The following set of methods are all category methods added by the [attributedlabel] feature.
// Each method has a final argument for specifying a range. If you don't specify a range then the
// modification will be applied to the entire string.
[text setFont:font range:rangeOfHello];
[text setFont:font range:rangeOfWorld];
[text setUnderlineStyle:kCTUnderlineStyleSingle
modifier:kCTUnderlinePatternSolid
range:rangeOfHello];
[text setTextColor:[UIColor redColor] range:rangeOfHello];
NIAttributedLabel* label = [[NIAttributedLabel alloc] initWithFrame:CGRectZero];
// We want this label to wrap over multiple lines. With CoreText we have to use either word or
// character wrapping in order to have a paragraph wrap over multiple lines. Truncation modes
// will only work for single lines of text and would require us to explicitly break the lines up
// with newline (\n) characters.
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.autoresizingMask = UIViewAutoresizingFlexibleDimensions;
label.frame = CGRectInset(self.view.bounds, 20, 20);
// When we assign the attributed text to the label it copies the attributed text object into the
// label. If we want to make any further stylistic changes then we must either use the label's
// methods or assign a modified attributed string object again.
label.attributedString = text;
[self.view addSubview:label];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment