I'm on the final stretch of my first simple iPhone application. I'm building an "about" view, with credits/info/etc.
I am failing on the simplest thing: how can I embed hyperlinks into the text? I'm current using a UIView with a UILabel for the text.
I've looked on here, and the sample apps, but not got anywhere. Should I use a UIWebView?
Thx.
Yep, use a UIWebView and put static HTML in it.
Like so:
[myWebView loadHTMLString:@"<html><head></head><body style=\"font-family: sans-serif;\"> .... </body></html>" baseURL:nil];
To launch the web browser at the specified url:
NSURL *target = [[NSURL alloc] initWithString:@"http://www.stackoverflow.com"];
[[UIApplication sharedApplication] openURL:target];
This code can be run anywhere. I sub-classed UILabel, added the touchedsEnded method and place it in there. (Don't forget to set labelname.userInteractionEnabled = YES;)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSURL *target = [[NSURL alloc] initWithString:@"http://www.stackoverflow.com"];
[[UIApplication sharedApplication] openURL:target];
}
UIWebView is probably the wrong way to do this. It's VERY much overkill for something like this. You're should 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.
You can trigger safari by calling UIApplication openURL: method with the URL you wish to display. This will close your app, and then open safari ( or mail / youtube / etc ).
You will want to make your link somehow, perhaps in a button. That part is up to you.
If you want to embed html content into your view, then by all means use a UIWebView.
Documentation:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With