更改 html 的链接颜色和下划线颜色转换为 AttributedString

Change links colors and underline color of html converted to AttributedString

我想给链接上色,并为从 html 收到的文本中的链接下划线添加特殊颜色。

这是我目前拥有的:

...

public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {

        if let htmlData = text.data(using: .utf8) {

            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]

            let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)

            let attributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.foregroundColor: UIColor.red]
            attributedString?.addAttributes(attributes, range: NSRange.init(location: 0, length: attributedString?.length ?? 0))
            return attributedString
        }

        return nil
    }
....

这是我得到的:

我正在寻找的是文本的常规颜色和链接的红色以及链接下划线的绿色

文本颜色为红色,因为您将整个属性字符串设置为红色:

let attributes: [NSAttributedString.Key: AnyObject] = 
                  [NSAttributedString.Key.foregroundColor: UIColor.red]
attributedString?.addAttributes(attributes, 
                  range: NSRange.init(location: 0, length: attributedString?.length ?? 0))

如果您希望它具有 "regular"(= 我猜是黑色?)颜色,请不要那样做并删除那些行。

下面是设置属性字符串中 link 颜色的方法:

这是设置不同下划线颜色所需的键:
NSAttributedString.Key.underlineColor


编辑:

为了使它更明确并将各个部分放在一起 — 这是您必须做的才能产生所需的 link 颜色:

textView.linkTextAttributes = [
    .foregroundColor: UIColor.black,
    .underlineColor: UIColor.red
]

(除了如上所述删除两行代码。)

如果您使用的是 UITextView,将 tintColor 设置为 UIColor.red 并删除以下内容就足够了:

let attributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.foregroundColor: UIColor.red]
attributedString?.addAttributes(attributes, range: NSRange.init(location: 0, length: attributedString?.length ?? 0))

所以它看起来像这样:

public func htmlStyleAttributeText(text: String) -> NSMutableAttributedString? {
    if let htmlData = text.data(using: .utf8) {
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]
        let attributedString = try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)
        return attributedString
    }
    return nil
}

//
textView.tintColor = .red
textView.attributedText = htmlStyleAttributeText(text: "random text <a href='http://www.google.com'>http://www.google.com </a> more random text")

输出: