Search code examples
iosswifthyperlinkuilabelnsattributedstring

hyperlink not highlighted in UILabel with NSAttributedText in iOS


I am displaying a label with an attributed text. The label contains some hyper links. I understand that these are only clickable in a textView however I thought that they would appear blue and underlined in a UILabel which has NSAttributedText.

In my case the link is not any different than the other text (not blue or underlined). Is there any property of the UILabel I need to change to make the link appear blue inside a UILabel?

let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
let attributes = [NSFontAttributeName: self.defaultFont(), NSParagraphStyleAttributeName: style]
let attributedString = NSAttributedString(string: "www.somelink.com", attributes: attributes)
label.attributedText = attributedString

Solution

  • You need to add NSLinkAttributeName attribute to your NSAttributedString like this:

    attributedString.addAttribute(NSLinkAttributeName, value: "www.somelink.com", range: attributedString.string.rangeOfString("www.somelink.com"))
    

    Please check the range for your needs.