iosnsattributedstring

Example of NSAttributedString with two different font sizes?


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.


Solution

  • Suppose your input text is “Some of this text is larger than the rest,” and you want to change the size of the word “larger.” Here’s how you would do it:

    let text = NSMutableAttributedString(
        "Some of this text is larger than the rest"
    )
    
    let range = text.mutableString.range(of: "larger")
    
    if range.location != NSNotFound {
        text.addAttribute(.font,
                          value: UIFont.systemFont(ofSize: 20),
                          range: range)
    }
    

    Or in Objective-C,

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
        initWithString:@"Some of this text is larger than the rest"];
    
    NSRange range = [text rangeOfString:@"larger"];
    
    if (range.location != NSNotFound) {
        [text addAttribute:NSFontAttributeName
                     value:[UIFont systemFontOfSize:20.0]
                     range:range];
    }
    

    The thing that might be confusing about setting the text size specifically is that you have to set the typeface and the size at the same time—each UIFont object encapsulates both of those properties.

    See the documentation of NSAttributedString.Key for the full list of NSAttributedString attributes.