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

时间:2019-03-20 15:33:58

标签: html ios swift nsattributedstring

我想给链接着色,并给从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
    }
....

这是我得到的: enter image description here

我要寻找的是文本的常规颜色,链接的红色,链接的下划线的绿色

2 个答案:

答案 0 :(得分:2)

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

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

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

以下是设置属性字符串中链接颜色的方法:
Change the color of a link in an NSMutableAttributedString

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


编辑:

要使其更加明确并将各个部分放在一起,这是产生所需链接颜色所需要做的:

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

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

答案 1 :(得分:0)

如果您使用的是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")

输出: enter image description here