user596741
user596741

Reputation: 21

How to detect the user click a hyper-link

My app will display some text, and I want to make the hyper-link be able to be clicked. I have some questions about this feature.

  1. How do I parse the text to be aware this is a link?

  2. Once a user click the link, I don't want the OS to switch to Safari and open the link, this is very bad because the user can not go back to my application. So I want to open the link within my application. As soon as the user click the link, my app will present a view modally to display the web content. Any advice would be appreciated.

Upvotes: 1

Views: 447

Answers (3)

Jake Marsh
Jake Marsh

Reputation: 865

You're going to want to check out a Github project called LRLinkableLabel.

It will auto-detect any URLs that are inside the .text property.

You can use it like so:

LRLinkableLabel *label = [[LRLinkableLabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 20.0)];
label.delegate = self;
label.text = @"Check out http://dundermifflin.com to find some great paper deals!";

Then just make sure self implements this method:

- (void) linkableLabel:(LRLinkableLabel *)label clickedButton:(UIButton *)button forURL:(NSURL *)url {
    [[UIApplication sharedApplication] openURL:url];
}

You can also use the linkColor and textColor properties to configure the appearance of the label. From this point you can use it just like any other UILabel.

Remember to set the delegate to nil when you're all done to make sure everything is all cleaned up.

Hope this helps.

Upvotes: 0

Greg
Greg

Reputation: 33650

If your text can be formatted as html with hyperlinks (<a> tags), you could use a UIWebView to display it.

The UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method is called when a user taps a link. Usually you would make your controller implement this method, and set the UIWebView's delegate to the controller.

Upvotes: 0

Simon Goldeen
Simon Goldeen

Reputation: 9080

  1. You probably want to subclass UILabel. When you change the text, have it try to see if the text is a hyperlink, if it is, set it to enable user interaction and change the text color to blue. When the user taps on the link, send a message to the main view controller (Possibly through delegation) to open the link.

  2. to display web content in your app, look into UIWebView.

Upvotes: 1

Related Questions