构建一个NSAttributedString
并将其设置为标签的attributedText
属性。
例子:
let html = "<strong>Choose Pasta</strong>: Fettuccine <strong>Add Toppings To The Pasta</strong>: Side Meatball <strong>Substitute Alfredo Sauce</strong>: Substitute Alfredo Sauce On Pasta <strong>Choose A Complimentary Soup Or Salad</strong>: Zuppa Toscana"
let richText = try NSAttributedString(
data: html.dataUsingEncoding(NSUTF8StringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding],
documentAttributes: nil)
label.attributedText = richText
如果您希望在代码中分配属性:
let richText = NSMutableAttributedString()
let normalAttributes = [ NSFontAttributeName: UIFont.systemFontOfSize(12) ]
let boldAttributes = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(12) ]
richText.appendAttributedString(NSAttributedString(string: "Choose Pasta", attributes: boldAttributes))
richText.appendAttributedString(NSAttributedString(string: ": Fettucine ", attributes: normalAttributes))
richText.appendAttributedString(NSAttributedString(string: "Add Toppings To The Pasta", attributes: boldAttributes))
richText.appendAttributedString(NSAttributedString(string: ": Side Meatball ", attributes: normalAttributes))
// etc.
label.attributedText = richText