UILabel在UITableViewCell中带有超链接,应该打开safari网络浏览器



我有一个带有两个标签(UILabel)的自定义UITableViewCell。表格单元格用于显示信息/文本。在其中一些单元格(不是全部)中,有以下方式设置的文本:

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

现在,我希望如果我单击此文本/链接,则野生动物园网络浏览器应打开此网页。我该怎么做?

最好的问候蒂姆。

将标签的 userInteractionEnabled 设置为 YES,并向其添加手势识别器:

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

然后实现操作方法:

- (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]];
    }
}

如果您使用UITextView而不是UILabel它将自动处理链接检测。 将视图的dataDetectorTypes设置为 UIDataDetectorTypeLink

在您的点击事件中,您可以通过以下代码打开 safari 浏览器 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];

最新更新