【问题标题】:NSAttributedString setting font size - swiftNSAttributedString 设置字体大小 - swift
【发布时间】:2019-12-11 08:28:07
【问题描述】:

所以我试图让下面的代码工作

     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)

我也尝试了以下方法,但失败了

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 ?? ""
    }
}

【问题讨论】:

标签: ios swift fonts nsattributedstring


【解决方案1】:

您正在将 html 转换为 NSAttributedString? 您可以将样式附加到字符串源。

示例: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()

结果:

【讨论】:

  • 没有帮助
  • 嗨@zhaozq,我有点惊讶人们就是这样做的,我想苹果会允许字体重新调整大小,而不是拥有完整的html样式标签跨度>
  • 我认为很难找到调整大小的范围,但使用 html 样式标签很容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 2019-09-29
  • 1970-01-01
相关资源
最近更新 更多