【问题标题】:Adding Font attributes to HTML rendered UILabel swift将字体属性添加到 HTML 呈现的 UILabel swift
【发布时间】:2017-11-13 22:43:51
【问题描述】:

我有一些 HTML 内容,我想在我的原生 UILabel 中呈现,但除此之外,我还必须向该 UILabel 添加自定义字体。我正在使用 NSAttributedString 来执行此操作,并使用以下代码在我的 UILabel 中呈现 HTML 内容。

 func htmlAttributedString() -> NSAttributedString? {
    guard let data = self.data(using: .utf16, allowLossyConversion: false) else {
        return nil
    }
    guard let html = try? NSMutableAttributedString(
        data: data,
        options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil) else { return nil }


    let attributes = [
        NSForegroundColorAttributeName: UIColor.lightGray,
        NSFontAttributeName : UIFont.systemFont(ofSize: 12)
    ]
    html.setAttributes(attributes, range: NSRange(0..<html.length))

    return html
}

var str = "Here is the <bold>string</bold> that i want to be bold.
messageLabel.attributedText = str.htmlAttributedString()

这里的问题是,当我在 HTML 呈现的属性字符串上应用字体属性时。然后像粗体这样的所有 HTML 格式都会丢失。

那么有没有一种方法可以在 HTML 呈现的属性字符串上应用一些选定的字体

【问题讨论】:

标签: html ios swift uilabel nsattributedstring


【解决方案1】:

根据您的要求替换字体。

func htmlAttriButedText(str : String) -> NSAttributedString{
        let attrStr = try! NSMutableAttributedString(
            data: str.data(using: String.Encoding.utf8, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
        attrStr.addAttribute(NSForegroundColorAttributeName, value: lightTextColor, range: NSMakeRange(0, attrStr.length))
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 13), range: NSMakeRange(0, attrStr.length))
        return attrStr
    }

【讨论】:

  • 对我来说,它替换了原始 HTML 内容中的所有格式
  • 由于粗体/斜体和大小在UIFont 内,因此它将失去其特殊性。迭代 NSFontAttributeName 并更改每个值,或者自己编辑 HTML。
猜你喜欢
  • 2015-03-29
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2011-04-15
  • 2012-04-02
  • 2011-10-25
相关资源
最近更新 更多