3

I have a custom UITableViewCell with two labels (UILabel). The table cells are used to display information / text. Inside some of these cells (not all) there is text in this way set:

cell.myTextlabel.text = @"http://www.google.de"

Now I want if I click this text / link, a safari webbrowser should open this webpage. How can I do this?

Best Regards Tim.

Tim
  • 13,228
  • 36
  • 108
  • 159

3 Answers3

9

Set userInteractionEnabled to YES of your label and add a gesture recognizer to it:

myLabel.userInteractionEnabled = YES;

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

Then implement the action method:

- (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]];
    }
}
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
  • It does the trick, but to make UILabel look like a link one has to subclass from UILabel to redefine the outlook (or to use 3rd party framework) and that's pretty annoying. – Artem Oboturov Oct 25 '11 at 10:23
  • 1
    On iOS 6.0 and later you can set the attributedText of the UILabel to have a blue color and an underline. – koen Oct 11 '13 at 16:53
  • why it giving me implicit conversion of 'NSInteger' (aka 'int') to 'UIEvent *' is disallowed with ARC when i tried to convert my project in ARC... it was working before. i have use your code id hitLabel = [self.view hitTest:[rec locationInView:self.view] withEvent:UIEventTypeTouches]; – BhavikKama Oct 21 '13 at 11:46
4

If you use a UITextView instead of a UILabel it will automatically handle link detection. Set the view's dataDetectorTypes to UIDataDetectorTypeLink.

Drew C
  • 6,408
  • 3
  • 39
  • 50
0

Inside your click event you can open safari browser by the following code   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];

Waqas Raja
  • 10,802
  • 4
  • 33
  • 38