Set part of a UILabel's text bold and another part italic

abinop picture abinop · Aug 24, 2015 · Viewed 7.8k times · Source

Is there a way to set part of a UILabel to be bold and another part italic?

As in

The quick brown fox jumps over the lazy dog.

It doesn't seem I can do this using TTTAttributedLabel

Answer

user4261201 picture user4261201 · Aug 24, 2015

You can do this by using NSMutableAttributedString

NSMutableAttributedString *strText = [[NSMutableAttributedString alloc] initWithString:@"Setting different for label text"];
[strText addAttribute:NSFontAttributeName
              value:[UIFont fontWithName:@"Helvetica-Bold" size:22]
              range:NSMakeRange(0, 10)];
[strText addAttribute:NSFontAttributeName
              value:[UIFont fontWithName:@"Helvetica-Italic" size:22]
              range:NSMakeRange(10, 10)];

Swift 4 code:

var strText = NSMutableAttributedString(string: "Setting different for label text")
strText.addAttribute(.font, value: UIFont(name: "Helvetica-Bold", size: 22)!, range: NSRange(location: 0, length: 10))
strText.addAttribute(.font, value: UIFont(name: "Helvetica-Italic", size: 22)!, range: NSRange(location: 10, length: 10))