1

In a swift iOS app, I have set a UILabel with an NSAttributedString on it. The AttributedString contains a URL set with

[NSLinkAttributeName:NSURL(string:urlStr)!].

All appears fine, meaning that the URL is clearly set as such, but when I tap it nothing happens.

Is there something I should do to make the URL work as one would expect (i.e fire Safari)?

I tried the following but it had no effect at all.

theLabel.userInteractionEnabled = true
Michel
  • 10,303
  • 17
  • 82
  • 179
  • 1
    Not getting what you want to do. If you want clickable control then why did not you put button instead of the label? – Chirag Shah Aug 11 '15 at 08:55
  • Have a look at http://stackoverflow.com/questions/19854506/uilabel-and-nslinkattributename-link-is-not-clickable – Mattias Aug 11 '15 at 08:55
  • Well. I have a text on a label and it would be convenient just to have part of the text to be clickable without having to make a specific component for that. I am looking for the simplest way. – Michel Aug 11 '15 at 08:58
  • Use UITextView and follow @Undeph answer – Hamza Ansari Aug 11 '15 at 09:09

2 Answers2

4

NSLinkAttribute is not working with UILabel as the handler method will respond to UItextViewDelegate Only.

You can either use. TTTAttributedLabel or can go with Replacing your UILabel with UITextView. After replacing the same use

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange

And don't forget to check for Detection and Behaviour property.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Rahul Verma
  • 688
  • 5
  • 17
1

Try this code :

var str: NSMutableAttributedString = NSMutableAttributedString(string: "Google")
        str.addAttribute(NSLinkAttributeName, value: "http://www.google.com", range: NSMakeRange(0, str.length))
        yourLabel.attributedText = str

This is not directly about the question but just to clarify, UITextField and UILabel does not support opening URLs. If you want to use UILabel with links you can check TTTAttributedLabel.

Also you should set dataDetectorTypes value of your UITextView to UIDataDetectorTypeLink or UIDataDetectorTypeAll to open URLs when clicked. Or you can use delegate method as suggested in the comments.

Dharmesh Dhorajiya
  • 3,976
  • 9
  • 30
  • 39