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

标签 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

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

最佳答案

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

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
]

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

关于html - 更改转换为 AttributedString 的 html 的链接颜色和下划线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55264585/

相关文章:

ios - 如何最好地确保在触发完成处理程序之前我拥有所有数据?

swift - 准备(对于 : sender:) not getting called during segue from button to tab bar controller (in Swift 4, Xcode 9)

javascript - HTML5 Canvas 透明度与 png 的怪异

javascript - 如何从文本文件中获取文本并将其显示在 <table> 中?

ios - 选择表格 View 单元格时无法推送我的 View Controller

swift - CGFloat 和 NSNumber 之间的转换,无需不必要地提升为 Double

ios - 过滤具有大量对象的数组的唯一名称

html - <div> 嵌套在 <p> 中

html - 在 html 中设置表格样式

ios - 选项卡更改时 View 会更改大小