0

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

jscs
  • 63,694
  • 13
  • 151
  • 195
abinop
  • 3,153
  • 5
  • 32
  • 46

2 Answers2

9

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))
user4261201
  • 2,324
  • 19
  • 26
  • 3
    Really!? There is no efficiency method to do this? Range?! and If I have a string where I have html tags?I must to build a method to do this? – ePascoal Jan 02 '17 at 10:16
6

Since iOS 6 you can set UILabel.attributedText to an NSAttributedString

var customString = NSMutableAttributedString(string: "my String");

customString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: NSRange(1...3))

var label  = UILabel();
label.attributedText = customString;
Undo
  • 25,519
  • 37
  • 106
  • 129
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44