0
votes

I have a UILabel in my storyboard, and I have an @IBOutlet to it in my controller. In my viewDidLoad, I am setting its attributed text with two different font sizes.

let str1 = NSMutableAttributedString(string: "first", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
let str2 = NSMutableAttributedString(string: "second", attributes: [NSFontAttributeName: UIFont.systemFontOfSize(10.0)])
str1.appendAttributedString(str2)
myLabel.attributedText = str1

Unfortunately, when I run the app, I can see the "firstsecond" string, but all in the same size (str1's 15-point font). Why is str2's 10-point font not being set?

Thanks in advance.

2

2 Answers

0
votes

You have to use addAttribute(...) to apply multiple attributes to the same string.

let first = "first"
let second = "second"
let string = NSMutableAttributedString(string: first + second)
string.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: NSMakeRange(0, first.characters.count))
string.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(10), range: NSMakeRange(first.characters.count, second.characters.count))
myLabel.attributedText = string
0
votes

The documentation for UILabel's attributedText property states:

assigning a new value updates the values in the font, textColor, and other style-related properties so that they reflect the style information starting at location 0 in the attributed string.

So whatever the style information is at location 0, that's what the label's going to be. That's why you're only seeing str1's 15 point font.