一尘不染

快速更改具有自己样式的HTML字符串上的字体

swift

我正在从Wordpress
API上获取HTML字符串,并将其解析为属性字符串以在我的应用程序中显示它。由于字符串具有自己的样式,因此显示不同的字体和大小,这会影响我们的设计选择。

我想做的是在整个属性字符串上更改字体及其大小。

我尝试在属性字符串的选项中执行此操作,但是它没有任何作用:

let attributedT = try! NSAttributedString(
            data: nContent!.decodeHTML().data(using: String.Encoding.unicode, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSFontAttributeName: UIFont(name: "Helvetica", size: 16.0)!],
            documentAttributes: nil)
        contentLbl.attributedText = attributedT

是否有人对如何实现这一目标有任何想法?

PS我知道我可以在字符串的开头或结尾添加CSS标记,但这会覆盖其中的其他样式吗?另外,如果这是一个有效的解决方案,请您提供一个示例来说明如何做?


阅读 307

收藏
2020-07-07

共1个答案

一尘不染

setAttributes将重置HTML中的所有属性。我写了一个扩展方法来避免这种情况:

斯威夫特4

public convenience init?(HTMLString html: String, font: UIFont? = nil) throws {
    let options : [NSAttributedString.DocumentReadingOptionKey : Any] =
        [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
         NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]

    guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
        throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
    }

    if let font = font {
        guard let attr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else {
            throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
        }
        var attrs = attr.attributes(at: 0, effectiveRange: nil)
        attrs[NSAttributedStringKey.font] = font
        attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
        self.init(attributedString: attr)
    } else {
        try? self.init(data: data, options: options, documentAttributes: nil)
    }
}

测试样本:

let html = "<html><body><h1 style=\"color:red;\">html text here</h1></body></html>"
let font = UIFont.systemFont(ofSize: 16)

var attr = try NSMutableAttributedString(HTMLString: html, font: nil)
var attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7ff19fd0a530> font-family: "TimesNewRomanPS-BoldMT"; font-weight: bold; font-style: normal; font-size: 24.00pt

attr = try NSMutableAttributedString(HTMLString: html, font: font)
attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7f8c0cc04620> font-family: ".SFUIText"; font-weight: normal; font-style: normal; font-size: 16.00pt
2020-07-07