0

我有一个带有文字的 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

之前的部分:粗体和之后的部分:正常字体

任何帮助/建议将不胜感激......

4

1 回答 1

1

构建一个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
于 2015-10-31T06:17:12.867 回答