如何在NSMutableAttributedString中禁用标签的下划线URL

问题描述 投票:1回答:1

我有一个带有属性文本的标签。文本有url链接,下划线为默认蓝色。如何删除NSMutableAttributedString的url下划线样式?

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
}

我试过上面的代码,但它仍然显示装饰链接。

attributed-string-url

ios swift nsmutableattributedstring
1个回答
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)

}
© www.soinside.com 2019 - 2024. All rights reserved.