【发布时间】:2020-06-08 08:46:18
【问题描述】:
我有以下扩展,可以将 html 格式的 API 响应转换为 NSAttributedString,使用 CSS 样式:
extension String {
public func convertHtmlToAttributedStringWithCSS(bodyFont: UIFont, h1Font: UIFont, csscolor: String, lineheight: Int, csstextalign: String) -> NSAttributedString? {
let modifiedString =
"<style>" +
"body{" +
"font-family: '\(bodyFont.fontName)'; " +
"font-size:\(bodyFont.pointSize)px; " +
"color: \(csscolor); " +
"line-height: \(lineheight)px; " +
"text-align: \(csstextalign); " +
"} " +
"h1{" +
"font-family: '\(h1Font.fontName)'; " +
"font-size:\(h1Font.pointSize)px; " +
"}" +
"</style>\(self)";
guard let data = modifiedString.data(using: .utf8) else {
return nil
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
catch {
print(error)
return nil
}
}
}
我这样称呼它:
self.CampaignDescriptionBody.attributedText = briefing!.convertHtmlToAttributedStringWithCSS(bodyFont: UIFont.systemFont(ofSize: 12), h1Font: UIFont.systemFont(ofSize: 15), csscolor: "grey", lineheight: 5, csstextalign: "left")
字体大小、文本对齐等工作正常。我的问题是,屏幕上的字体根本不像系统字体,现在似乎是旧金山。
这是 2 个 UILabel 在屏幕上彼此相邻的屏幕截图。 “Campaign Description”在界面生成器中设置为“System Bold 15” “Exklusivität”是 API 响应的一部分,它被转换为 NSAttributedString,因此它应该使用相同的字体呈现,但显然不是。
有谁知道我在这里做错了什么?
【问题讨论】:
-
试试
font-family: '-apple-system'。 -
@Gereon: Bingo - 谢谢!!
-
好的,很好:) - 我不是 100% 确定。那么我将添加这个作为答案。
标签: nsattributedstring swift5 xcode10