How to include a hyperlink in a label in Cocoa Touch?
I'm trying to find a simple way to include a hyperlink w开发者_StackOverflow中文版ithin 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
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.
Instead of calling Safari you could start a UIWebView. You have more control about the actions the user can do at that web page.
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;
}
精彩评论