将UILabel文本的一部分设置为粗体,将另一部分设置为斜体

时间:2015-08-24 06:39:03

标签: ios cocoa-touch uilabel text-styling

有没有办法将UILabel的一部分设为粗体,另一部分设为斜体?

  

快速棕色狐狸跳过这只懒狗。

我似乎无法使用TTTAttributedLabel

执行此操作

2 个答案:

答案 0 :(得分:9)

您可以使用 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代码:

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))

答案 1 :(得分:6)

从iOS 6开始,您可以将UILabel.attributedText设置为NSAttributedString

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

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

var label  = UILabel();
label.attributedText = customString;