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)
我正在寻找的是文本的常规颜色、链接的红色和链接下划线的绿色
文本的颜色为红色,因为您将整个属性字符串设置为红色:
\n\nlet attributes: [NSAttributedString.Key: AnyObject] = \n [NSAttributedString.Key.foregroundColor: UIColor.red]\nattributedString?.addAttributes(attributes, \n range: NSRange.init(location: 0, length: attributedString?.length ?? 0))\nRun Code Online (Sandbox Code Playgroud)\n\n如果您希望它具有“常规”(=我猜是黑色?)颜色,请不要这样做并删除这些行。
\n\n以下是如何设置属性字符串中链接的颜色:
\n\xe2\x86\x92 Change the color of a link in an NSMutableAttributedString
这是您需要用来设置不同下划线颜色的键:
\n NSAttributedString.Key。下划线颜色
编辑:
\n\n为了使其更明确并将各个部分放在一起 \xe2\x80\x94 ,您必须执行以下操作才能产生所需的链接颜色:
\n\ntextView.linkTextAttributes = [\n .foregroundColor: UIColor.black,\n .underlineColor: UIColor.red\n]\nRun Code Online (Sandbox Code Playgroud)\n\n(除了如上所述删除两行代码之外。)
\n| 归档时间: |
|
| 查看次数: |
2540 次 |
| 最近记录: |