ios - NSAttributedString 不会显示正确的字体

标签 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)
        }
    }
}

最佳答案

如果您希望从生成的 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)
        }
    }
}

关于ios - NSAttributedString 不会显示正确的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532626/

相关文章:

iOS Swift 弹出 View Controller

ios - 如何阻止 UILabel 最后修剪空间?

ios - 调整 UILabel 字体大小以适合文本

ios - 格式化数据 CIColorCube

ios - 核心数据模型文件不在 bundle 中

ios - 错误 "ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386"

iOS:如何自定义JSQMessagesCollectionview?

ios - 从 UITableView(WEPopover) 触发 UIViewController 的更改

ios - 使用多部分和不记名 token 上传图像

ios - 有没有办法让 UIButton 与 UILabel 中的文本换行?