Example of NSAttributedString with two different font sizes? Example of NSAttributedString with two different font sizes? ios ios

Example of NSAttributedString with two different font sizes?


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.


Swift 3 Solution

Also, you can use the append function instead of specifying indices in ObjC or Swift:

let attrString = NSMutableAttributedString(string: "Presenting The Great...",                                           attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ])attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",                                            attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 40) ]))


[UPDATE] Swift 5 Solution:

let attrString = NSMutableAttributedString(string: "Presenting The Great...",                                           attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]);attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",                                            attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)]));

Swift 4 Solution:

let attrString = NSMutableAttributedString(string: "Presenting The Great...",                                       attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]);attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",                                        attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 36)]));