首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >TextView的超文本标记语言解析(Swift 4问题)

TextView的超文本标记语言解析(Swift 4问题)
EN

Stack Overflow用户
提问于 2018-02-21 19:08:51
回答 2查看 170关注 0票数 0

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上:

代码语言:javascript
复制
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上:

代码语言:javascript
复制
    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结果:

Swift 4结果:

我很怀念Swift 4的边界。有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-27 19:05:53

错误是因为我用Label代替了TextView的attributedText。它可以很好地与textView配合使用。

票数 1
EN

Stack Overflow用户

发布于 2018-07-12 09:06:29

如果辅助功能字体不同于默认字体,在html中调整UILabel attributedString的大小将会很有趣。在ios 11.2上测试,您将发现它们

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48904356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档