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

问题描述 投票:1回答:2

我想为链接添加颜色,并为我从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

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

html ios swift nsattributedstring
2个回答
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


3
投票

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

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
]

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

© www.soinside.com 2019 - 2024. All rights reserved.