George
George

Reputation: 3708

How to make a link clickable in custom UITableViewCell in swift

I am having a custom uitableviewcell and it has a label, I am detecting for any links in the label text and if present then I highlight it. But the problem is that I want to make the link clickable. But when I click on the link didSelectRowAtIndexPath is invoked and another page is loaded.

What I am trying to achieve is that when I click on the link(only on the link and not on the cell) corresponding webpage must open up instead of calling didSelectRowAtIndexPath. I searched and found some third party library. But my question is, can it be achieved without using a third party library? If so, how can it be done.

Here is the code which I am using to highlight links

labelText.addAttribute(NSLinkAttributeName, value: "http://linktosite" , range: urlRange)

Hope you understand the problem

Thanks in advance.

Upvotes: 2

Views: 3452

Answers (1)

poojathorat
poojathorat

Reputation: 1220

You can write a condition in didSelectRowAtIndexPath delegate method of iOS as if UILabel consists of link then open URL else other part.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    DetailViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(cell.labelText.text == @"Link")
{
      //Open in safari
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:cell.labelText.text]];
}
else
{

}
}

Or you can add tap gesture to label & open URL as

cell.labelText.userInteractionEnabled = YES;

UITapGestureRecognizer *gestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openUrl:)];
gestureRec.numberOfTouchesRequired = 1;
gestureRec.numberOfTapsRequired = 1;
[cell.labelText addGestureRecognizer:gestureRec];

and implement action method as

- (void)openUrl:(id)sender
{
UIGestureRecognizer *rec = (UIGestureRecognizer *)sender;

id hitLabel = [self.view hitTest:[rec locationInView:self.view] withEvent:UIEventTypeTouches];

if ([hitLabel isKindOfClass:[UILabel class]]) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:((UILabel *)hitLabel).text]];
}
}

Upvotes: 2

Related Questions