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

Lud*_*uda 1 html nsattributedstring ios swift

我想为链接着色,并为从 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
    }
....
Run Code Online (Sandbox Code Playgroud)

这就是我得到的: 在此输入图像描述

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

Mis*_*cha 5

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

\n\n
let attributes: [NSAttributedString.Key: AnyObject] = \n                  [NSAttributedString.Key.foregroundColor: UIColor.red]\nattributedString?.addAttributes(attributes, \n                  range: NSRange.init(location: 0, length: attributedString?.length ?? 0))\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您希望它具有“常规”(=我猜是黑色?)颜色,请不要这样做并删除这些行。

\n\n

以下是如何设置属性字符串中链接的颜色:
\n\xe2\x86\x92 Change the color of a link in an NSMutableAttributedString

\n\n

这是您需要用来设置不同下划线颜色的键:
\n NSAttributedString.Key。下划线颜色

\n\n
\n\n

编辑:

\n\n

为了使其更明确并将各个部分放在一起 \xe2\x80\x94 ,您必须执行以下操作才能产生所需的链接颜色:

\n\n
textView.linkTextAttributes = [\n    .foregroundColor: UIColor.black,\n    .underlineColor: UIColor.red\n]\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n