Question

In the below code I am detecting the url from string. now I need to put hyperlink only to detected "url" and assign to UILabel whenever I click on this url it should go to browser, how to do this?

Code:

NSString *string = descPost.text;
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches)
{
    if ([match resultType] == NSTextCheckingTypeLink)
    {
        NSURL *url = [match URL];
        NSLog(@"found URL: %@", url);
    }
}
Was it helpful?

Solution

What you should do is you should create a UITapGestureRecognizer on a UILabel and when that UILabel is tapped on, you should open the url.

Create the gesture like this:

UITapGestureRecognizer *gr = 
 [[UITapGestureRecognizer alloc] initWithTarget:self 
                                         action:@selector(myAction:)];
[myLabel addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;

Next write this delegate method when tap is pressed:

- (void) myAction: (UITapGestureRecognizer *) gr {
    // write code to open the url here
    [[UIApplication sharedApplication] openURL:url];
}

OTHER TIPS

My suggestion is, use a UIButton set clear color in background view, and make a IBAction method to manage the action of open URL.

in .h

-(IBAction)openUrl:(id)sender; 

in .m

-(IBAction)openUrl:(id)sender{
[[UIApplication sharedApplication] openURL:url];

}

Like our friend said.

My suggestion is, put you link on button instead of label because label has not it own click event/action so you need to use tap gesture for apply clickable feature on label where button has it's own forControlEvents so you can easily handle it. remain thing for an underline of link then put background image of button that look like an underline.

For convert URL to NSString

NSString *urlString = [myURL absoluteString];

Otherwise all the information you can get from @Khawar Ali's answer :)

Try this one :

 UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 100, 200, 40)]; // according your requirement
 yourLabel.userInteractionEnabled = YES;
 UITapGestureRecognizer *linked = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(LinkedToURL:)];
 [yourLabel addGestureRecognizer:linked];
 linked.numberOfTapsRequired = 1;
 linked.cancelsTouchesInView = NO;
 [self.view addSubview:yourLabel];

 - (void) LinkedToURL: (UITapGestureRecognizer *) linked
 {
    // write your code here for linked with your urls
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top