Search code examples
iosswiftnsmutableattributedstring

How to disable underlining urls in NSMutableAttributedString for a label


I have a label with attributed text. The text has url link which gets underlined with default blue color. How to remove the url underline style for 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
}

I tried with the above code, but it still show the decorated link.

attributed-string-url


Solution

  • enumerate through the attributes in the attributedString, and remove those for links…

    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)
    
    }