Example of NSAttributedString with two different font sizes?

Le Mot Juiced picture Le Mot Juiced · Aug 21, 2013 · Viewed 79.6k times · Source

NSAttributedString is just really impenetrable to me.

I want to set a UILabel to have text of different sizes, and I gather NSAttributedString is the way to go, but I can't get anywhere with the documentation on this.

I would love it if someone could help me with a concrete example.

For instance, let's say the text I wanted was:

(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"

Can somebody show me how to do that? Or even, a reference that's plain and simple where I could learn for myself? I swear I've tried to understand this through the documentation, and even through other examples on Stack Overflow, and I'm just not getting it.

Answer

bdesham picture bdesham · Aug 21, 2013

You would do something like this…

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:20.0]
              range:NSMakeRange(24, 11)];

This will set the last two words in 20-point text; the rest of the string will use the default value (which I believe is 12 points). The thing that might be confusing about setting the text size is that you have to set the typeface and the size at the same time—each UIFont object encapsulates both of those properties.