我想为链接添加颜色,并为我从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
}
....
我要找的是文本的常规颜色和链接的红色以及链接下划线的绿色
如果您使用的是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")
文本的颜色为红色,因为您为整个属性字符串将其设置为红色:
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
]
(除了如上所述删除两行代码。)