Gary Haran
Gary Haran

Reputation: 687

How can you bold just one word in a UILabel?

It's easy to display a single label with entirely the same text but what happens when you want to display one word in bold?

Example:

All your bases are belong to us.

Upvotes: 8

Views: 4122

Answers (3)

westsider
westsider

Reputation: 4985

As Evan Mulawski wrote, UILabel won't get you what you want. For that matter, neither will UITextField nor UITextView.

Another approach would be to subclass UIView and write a -drawRect: method that does what you want. You might look at

  • CGContextShowTextAtPoint
  • [NSString drawAtPoint:withFont:]
  • [NSString sizeWithFont:]

If you won't be requiring a lot of line breaks and wrapping, then you could probably craft something fairly easily.

UIWebView would probably be faster but it seems like a lot of overhead for something as simple as a styled label.

Upvotes: 1

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

UILabel itself cannot draw a label with different attributes/fonts within the text. But Core Text can. You can create a subclass of UILabel that wraps an attributed string and uses Core Text to draw it. You can handle the drawing as in this sample code from the Core Text programming guide:

// Build up your attributed string, then...
CTLineRef line = CTLineCreateWithAttributedString(attrString);

// Set text position and draw the line into the graphics context
CGContextSetTextPosition(context, 10.0, 10.0);
CTLineDraw(line, context);
CFRelease(line);

Upvotes: 7

Evan Mulawski
Evan Mulawski

Reputation: 55334

Unfortunately, this is currently not possible. You could, however, subclass UILabel and include this functionality.

Another possibility would be using a UIWebView, but this requires using HTML tags and the loadHTML: method.

Upvotes: 1

Related Questions