HTML样式中的NSMutableAttributedString错误地标记了项目符号和数字

时间:2018-09-17 15:58:08

标签: html ios nsattributedstring nsmutableattributedstring

我在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
        }
    }

}

我正在通过olul标签运行一些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

当我将其放入标签时,即使strongema标签位于{{ 1}}。

Display of UILabel with attributed text

我猜想这是li中的一个错误,并且准备提起雷达,但是我想看看StackOverflow是否可以首先在我的代码中找到一个错误。

0 个答案:

没有答案