user965985
user965985

Reputation: 313

How to include a hyperlink in a label in Cocoa Touch?

I'm trying to find a simple way to include a hyperlink within the text of a label in my iOS app. The goal is to have the user tap the URL and the app will open a Safari browser with that URL.

I've read about including a button with the URL as the label, but that's not going to work for my application.

Is there a simple way to do this?

Thanks so much

Upvotes: 2

Views: 1331

Answers (3)

David M. Syzdek
David M. Syzdek

Reputation: 15788

You need to enable user interactions for your label and then override the - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event method to handle the touch.

To enable user interactions set the following property on your UILabel:

urlLabel.userInteractionEnabled = YES;

An example of touchedEnded:WihEvent: in your UIViewController:

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch  * touch;
   CGPoint    currPt;

   if ((touches = [event touchesForView:urlLabel]))
   {
      touch = [touches anyObject];
      currPt  = [touch locationInView:self.view];
      if ( (currPt.x >= urlLabel.frame.origin.x) &&
           (currPt.y >= urlLabel.frame.origin.y) &&
           (currPt.x <= (urlLabel.frame.origin.x + urlLabel.frame.size.width)) &&
           (currPt.y <= (urlLabel.frame.origin.y + urlLabel.frame.size.height)) )
      {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlLabel.text]];
         return;
      };
   };

   return;
}

Upvotes: 0

vikingosegundo
vikingosegundo

Reputation: 52227

You can achieve this by using NSArrtibutedStrings — but I would recommend to use some wrapper around this C-functions. I like OHAttributedLabel.

The demo included shows exactly, how hyperlinks can be handled.

Upvotes: 1

ott--
ott--

Reputation: 5722

Instead of calling Safari you could start a UIWebView. You have more control about the actions the user can do at that web page.

Upvotes: 0

Related Questions