【问题标题】:HTML hyperlink to NSAttributedString did not style到 NSAttributedString 的 HTML 超链接没有样式
【发布时间】:2020-04-15 07:44:53
【问题描述】:

我正在尝试从给定的 HTML 字符串创建 NSAttributedString,带有段落和超链接。一切都很好,除了样式超链接。 我的样式代码如下所示:

func htmlAttributed() -> NSAttributedString? {
    do {
        let htmlCSSString = "<style>" +
            "* {" +
                "font-size: 12px !important;" +
                "color: #9D9B98 !important;" +
            "}" +
            "p" +
            "{" +
                "font-size: 12px !important;" +
                "color: #9D9B98 !important;" +
                "font-family: Helvetica !important;" +
            "}" +
            "a" +
            "{" +
                "font-size: 12px !important;" +
                "color: hotpink !important;" +
                "font-family: Helvetica !important;" +
            "}" +
            "a:link" +
            "{" +
            "text-decoration: none !important;" +
            "color: hotpink !important;" +
            "}" +
            "a:visited" +
            "{" +
            "text-decoration: none !important;" +
            "}" +
            "</style> \(self)"

        guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
            return nil
        }

        return try NSAttributedString(data: data,
                                      options: [.documentType: NSAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                      documentAttributes: nil)
    } catch {
        print("error: ", error)
        return nil
    }
}

当我在网站上打开它时效果很好。但是转换为 NSAttributedString 仅适用于 p 标记,不适用于超链接。

为了测试,我使用这部分代码

<p>This is not a link <b><a class='test' href='test' target='_blank'>This is a link</a></b></p>

在 w3c 操场上,我有:

在 iPhone 上我有:

【问题讨论】:

    标签: ios swift iphone nsattributedstring


    【解决方案1】:

    如果您使用的是UILabel,请尝试改用UITextView,并使用linkTextAttributes 更改链接颜色。这样您的链接也将是可点击的。

    textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemPink]
    
    

    【讨论】:

    • 很遗憾,在这种情况下 UITextView 是不可能的。
    • 我找不到适合 UILabel 的解决方案。这似乎是 NSAttributedString 对待链接的方式。
    猜你喜欢
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多