简体   繁体   English

NSAttributedString 设置字体大小 - swift

[英]NSAttributedString setting font size - swift

So I am trying to get the following code to work所以我试图让下面的代码工作

     return try NSAttributedString(data: data, attributes:[ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0) ], options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)

I have tried the following too but just fails我也尝试过以下方法但失败了

extension String {
    var htmlToAttributedString: NSAttributedString? {

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
               let font = UIFont.systemFont(ofSize: 72)
               let attributes = [NSAttributedString.Key.font: font]
            return try NSAttributedString(data: data,  attributes: attributes, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

You are convert html to NSAttributedString?您正在将 html 转换为 NSAttributedString 吗? You can append style to the string source.您可以将样式附加到字符串源。

example: https://stackoverflow.com/a/41519178/4368670示例: https : //stackoverflow.com/a/41519178/4368670

extension String {
    func htmlToAttributedString(fontName: String = "Chalkduster", fontSize: Float = 72) -> NSAttributedString? {
        let style = "<style>body { font-family: '\(fontName)'; font-size:\(fontSize)px; }</style>"
        guard let data = (self + style).data(using: .utf8) else {
            return nil
        }
        return try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
    }
}
let html = "<div>content</div>"
lebal.attributedText = html.htmlToAttributedString()

result:结果:

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM