gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:44 25 4
gpt4 key购买 nike

我想为链接着色,并为从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com