我在NSMutableAttributedString
中添加了一个便捷构造函数,以接受String
的HTML和字体。
extension NSMutableAttributedString {
// Convert HTML, but override the font. This copies the symbolic traits from the source font, so things like
// bold and italic are honored.
convenience init?(html: String, font: UIFont) {
guard let data = html.data(using: .utf16, allowLossyConversion: true) else {
preconditionFailure("string->data can't fail when lossy conversion is allowed")
}
do {
try self.init(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
enumerateAttribute(.font, in: NSMakeRange(0, length), options: .longestEffectiveRangeNotRequired) { value, range, stop in
guard
let currentFont = value as? UIFont,
let newDescriptor = font.fontDescriptor.withSymbolicTraits(currentFont.fontDescriptor.symbolicTraits)
else {
return
}
let newFont = UIFont(descriptor: newDescriptor, size: font.pointSize)
addAttribute(.font, value: newFont, range: range)
}
} catch {
return nil
}
}
}
我正在通过ol
和ul
标签运行一些HTML,并将它们放在标签上。
let html = [
"<ul>",
"<li>not a link</li>",
"<li>",
"<a href=\"https://www.google.com\">link</a>",
"</li>",
"<li>",
"<strong><a href=\"https://www.google.com\">bold link</a></strong>",
"</li>",
"<li>",
"<em><a href=\"https://www.google.com\">italic link</a></em>",
"</li>",
"</ul>",
"<ol>",
"<li>not a link</li>",
"<li>",
"<a href=\"https://www.google.com\">link</a>",
"</li>",
"<li>",
"<strong><a href=\"https://www.google.com\">bold link</a></strong>",
"</li>",
"<li>",
"<em><a href=\"https://www.google.com\">italic link</a></em>",
"</li>",
"</ol>",
].joined(separator: "\n")
guard let string = NSMutableAttributedString(html: html, font: UIFont.systemFont(ofSize: 18)) else {
fatalError()
}
label.attributedText = string
当我将其放入标签时,即使strong
,em
和a
标签位于{{ 1}}。
我猜想这是li
中的一个错误,并且准备提起雷达,但是我想看看StackOverflow是否可以首先在我的代码中找到一个错误。