NSAttributedString将不会显示正确的字体

时间:2018-01-31 00:24:39

标签: ios swift uilabel nsattributedstring

我有一个标签,通过此NSAttributedString功能显示HTML。 问题是我想为它添加一个自定义字体,但它不会添加字体。

我做错了什么?

这是我的代码:

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)

        }catch{
            return NSAttributedString.init(string: self, attributes: titleAttributes)
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您希望替换生成的HTML中的所有字体设置,则需要在从HTML字符串创建属性字符串后应用titleAttributes

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            let res = try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
            let mutable = res.mutableCopy() as! NSMutableAttributedString
            mutable.addAttributes(titleAttributes, range: NSRange(location: 0, length: res.length))

            return mutable
        }catch{
            return NSAttributedString.init(string: self, attributes: titleAttributes)
        }
    }
}