同一个 UILabel 中的不同字体

Different fonts in same UILabel

我有一个带有文本的 UILabel

Choose Pasta: Fettuccine
Add Toppings To The Pasta: Side Meatball
Substitute Alfredo Sauce: Substitute Alfredo Sauce On Pasta
Choose A Complimentary Soup Or Salad: Zuppa Toscana

如何为这个 UILabel 应用不同的粗体和普通字体,使其显示得像

选择意大利面:宽面条 在面食中添加配料:配肉丸 替代阿尔弗雷多酱:在意大利面上替代阿尔弗雷多酱 选择一份免费的汤或沙拉:Zuppa Toscana

前面部分:粗体,后面部分:普通字体

任何 help/suggestions 将不胜感激...

构建一个 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