ios - HTML 解析为 TextView(Swift 4 问题)

标签 ios swift swift4

HtmlString = <table border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td>as</td><td> </td><td> </td><td> </td></tr><tr><td>a</td><td>a</td><td>a</td><td> </td></tr><tr><td>a</td><td> </td><td> </td><td>a</td></tr></tbody></table>

我对字符串进行了扩展,将字符串 (html) 解析为 NSAttributedString。

在 swift 3 上:

guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

guard let htmlString = try? NSMutableAttributedString(
    data: data,
    options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
    documentAttributes: nil) else { return nil }

let fullRange = NSRange(location: 0, length: htmlString.length);
    htmlString.enumerateAttribute(NSFontAttributeName, in: fullRange, options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: {
        (attributes, range, stop) -> Void in

        let newFont = UIFont.preferredFont(fontName: FontName.kHelveticaNeueLight, fontSize: FontSize.kTextView);
        htmlString.addAttribute(NSFontAttributeName, value: newFont, range: range);
    });

    htmlString.addAttribute(NSForegroundColorAttributeName, value:Color.kGrayDark, range:fullRange)

return htmlString;

在 swift 4 上:

    guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
    guard let htmlString = try? NSMutableAttributedString(
        data: data,
        options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
        documentAttributes: nil) else { return nil }
    let fullRange = NSRange(location: 0, length: htmlString.length);

    htmlString.enumerateAttribute(NSAttributedStringKey.font, in: fullRange, options: NSAttributedString.EnumerationOptions.longestEffectiveRangeNotRequired, using: {
        (attributes, range, stop) -> Void in
        let newFont = UIFont(name: FontName.regular.value, size: FontSize.html)
        htmlString.addAttribute(NSAttributedStringKey.font, value: newFont ?? UIFont.systemFont(ofSize: FontSize.html), range: range);
    });

    htmlString.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.html(), range:fullRange)
    return htmlString;

swift 3 结果:

enter image description here

swift 4 结果:

enter image description here

我想念 Swift 4 上的边框。有什么建议吗?

最佳答案

错误是因为我对 attributedText 使用了 Label 而不是 TextView。它适用于 textView。

关于ios - HTML 解析为 TextView(Swift 4 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904356/

相关文章:

javascript - 修复了 ios 上的导航在水平滚动时移动的问题

swift - 如何在核心数据中使用 swift 4 Codable?

javascript - EvaluateJavascript() 不会执行

ios - 如何最好地Firebase查询来观察Bool属性的变化

ios - Facebook 快速登录

ios - 如何检测一个sknode悬停在另一个sknode上?

swift - RxAlamofire 使用 json 主体进行 post 调用

ios - 循环打开 UIDocument

iphone - 通过推送和模态 Segue 重用 View Controller

ios - 一个 View 中的两个操作表