Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a link using NSMutableAttributedString that is not underlined?

Tags:

ios

swift

I'm trying to programmatically add a link to the last part of a UILabel, but not have the entire UILabel become a link (ignore the ranges as I changed the input string).

let mutableString = NSMutableAttributedString(string: "This is a string. This is the link that should be underlined")

mutableString.addAttribute(NSLinkAttributeName, value: "www.website.com", range: NSMakeRange(57, 16))

self.label.attributedText = mutableString

The above code does what I want functionally, but now the link is underlined, which is not what I want. So I added the following line:

mutableString.addAttribute(NSUnderlineColorAttributeName, value: NSUnderlineStyle.StyleNone.rawValue, range: NSMakeRange(57, 16))

Now the text in the range won't appear at all. Any ideas as to how to make this work?

like image 917
Alex S Avatar asked May 24 '26 21:05

Alex S


1 Answers

Try this

EDITED

    let mutableString = NSMutableAttributedString(string: "This is a string. This is the link that should be underlined")

    mutableString.addAttribute(NSLinkAttributeName, value: "www.website.com", range: NSMakeRange(0, 16))
    mutableString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleNone.rawValue, range: NSMakeRange(0, 16))
    mutableString.addAttribute(NSUnderlineColorAttributeName, value: UIColor.clearColor(), range: NSMakeRange(0, 16))

enter image description here

I hope this helps you, for me works like charm

like image 53
Reinier Melian Avatar answered May 26 '26 12:05

Reinier Melian