34

I want to use attributed strings with NSLinkAttributeName to create clickable links inside a UILabel instance within my iOS 7 project, which is now finally possible without using external libraries.

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];

NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                          url, NSLinkAttributeName, nil];

Applying the attribute on a string displays the text as blue & underlined, but nothing happens on click/tap. User interaction is enabled for the label. Does anybody know how to do this? Thanks!

Habizzle
  • 2,971
  • 3
  • 20
  • 23

1 Answers1

49

I can answer my own question now: I am using UITextView instead of UILabel now. I have formatted the UITextView to look and behave like my labels and added:

UITextView *textView = [[UITextView alloc] init];
textView.scrollEnabled = NO;
textView.editable = NO;
textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
textView.delegate = self;

Don't forget to set the delegate, you have to implement UITextViewDelegate! Now we implement the delegate method:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
{
     return YES;
}

This automatically opens the provided the NSURL-instance from the attributed string in my question on click/tap.

Remember: This works on iOS 7 only, for legacy support you need external libraries

UPDATE:

Making the UITextViews behave just like labels was a total mess in the end and i stumbled upon some hideous iOS-behaviours. I ended up using the TTTAttributedLabel library which is simply great and allowed me to use labels instead of UITextViews.

Piyush Dubey
  • 2,416
  • 1
  • 24
  • 39
Habizzle
  • 2,971
  • 3
  • 20
  • 23
  • 2
    The .textContainer is key here. I swapped my labels out for textviews and had the links working but it was throwing off the layout and look. – WCByrne Feb 13 '14 at 17:30
  • 1
    Surely you mean UITextViewDelegate not UITextFieldDelegate – Mark Bridges Mar 27 '14 at 14:23
  • yeah of course, I have corrected the mistake - thanks. – Habizzle Mar 28 '14 at 12:19
  • 5
    @max.mustermann: Can you elaborate on what issues led you to abandon this approach? – Lily Ballard Feb 12 '15 at 22:46
  • @WCByrne can you explain that? I would like to do the same. Thanks a lot. – Ricardo Jun 01 '16 at 14:20
  • 2
    @Ricardo, just pointed out that setting the `textView.textContainer.---` values are the key to getting UITextViews to layout like UILabels. That is to say, those values, adjust the padding of the text in the TextView; setting them to zero give you the look of a UILabel with the functionality of a UITextView. – WCByrne Jun 02 '16 at 19:16
  • +1 @WCByrne, ABSOLUTELY make sure you set the .textContainer values . This ensured that UITableViewAutomaticDimension worked properly for my dynamic height cells. – cloudcal Oct 19 '16 at 23:57