【问题标题】:Different fonts in same UILabel同一个UILabel中的不同字体
【发布时间】:2015-10-31 06:04:51
【问题描述】:

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

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

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

【问题讨论】:

  • 使用属性字符串..
  • 检查一下:stackoverflow.com/questions/11031623/…> 和这个 stackoverflow.com/questions/3586871/…>

标签: iphone xcode ios9.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

【讨论】:

  • 如果 UILabel 文本是静态的,这是正确的,但是我们有一个动态的 UILabel,其中文本会发生变化。所以需要像“之前的部分:作为粗体和之后的部分:作为普通字体”
  • 当然你也可以通过在代码中粘贴字符串来创建HTML。
  • 对不起,我没听懂"通过将字符串粘贴到代码中来创建 HTML"
  • 如:var html = "&lt;strong&gt;"; html += "Hello"; html += "&lt;/strong&gt;"
猜你喜欢
  • 2012-05-01
  • 2015-09-02
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多