我有一个带有属性文本的标签。文本具有url链接,该链接下划线带有默认的蓝色。如何删除NSMutableAttributedString
的网址下划线样式?
func htmlToAttributedString(_ html: String) -> NSAttributedString? {
guard let data = NSString(string: html).data(using: String.Encoding.utf8.rawValue) else { return nil }
do {
let attrStr = try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
let range = NSRange(location: 0, length: attrStr.length)
let str = NSMutableAttributedString(attributedString: attrStr)
str.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)], range: range)
str.addAttribute(NSAttributedString.Key.underlineStyle, value: 0, range: range)
return NSAttributedString(attributedString: str.attributedSubstring(from: range))
} catch {}
return nil
}
我尝试了上面的代码,但是它仍然显示修饰的链接。
答案 0 :(得分:1)
enumerate
通过attributedString
中的属性,并删除链接的属性...
attributedString.enumerateAttributes(in: NSRange(location: 0, length: attributedString.length), options: []) { attributes, range, stop in
attributedString.removeAttribute(.link, range: range)
attributedString.removeAttribute(.foregroundColor, range: range)
attributedString.removeAttribute(.underlineStyle, range: range)
}