【发布时间】: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 呈现的属性字符串上应用一些选定的字体
【问题讨论】:
-
@UmaMadhavi 您的链接对我有用。谢谢
标签: html ios swift uilabel nsattributedstring