Я добавил вспомогательный конструктор к 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
}
}
}
Я запускаю некоторый HTML с использованием тегов ol
и ul
черезэто и размещение их на этикетке.
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
теги находятся внутри li
.
![Display of UILabel with attributed text](https://i.stack.imgur.com/pvohn.png)
Я предполагаю, что это ошибка в NS(Mutable)AttributedString
, и я готов подать радар, но я хотел посмотреть, сможет ли StackOverflow сначала найти ошибку в моем коде.