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

abi*_*nop 0 cocoa-touch text-styling uilabel ios

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

如在

敏捷的棕色狐狸跳过了懒狗.

我似乎无法使用TTTAttributedLabel执行此操作

use*_*201 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)];
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

  • 真!?这样做没有效率方法吗?范围?!如果我有一个字符串,我有html标签?我必须建立一个方法来做到这一点? (2认同)

Dan*_*rom 6

从iOS 6开始,您可以设置UILabel.attributedTextNSAttributedString

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

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

var label  = UILabel();
label.attributedText = customString;
Run Code Online (Sandbox Code Playgroud)