【问题标题】:UILabel with a hyperlink inside a UITableViewCell should open safari webbrowser?在 UITableViewCell 中带有超链接的 UILabel 应该打开 safari 网络浏览器吗?
【发布时间】:2011-05-08 16:56:16
【问题描述】:

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

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

现在我想如果我点击这个文本/链接,一个 safari 网络浏览器应该会打开这个网页。我该怎么做?

最好的问候蒂姆。

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    将标签的 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];
    

    然后实现action方法:

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

    【讨论】:

    • 它可以解决问题,但要使 UILabel 看起来像一个链接,必须从 UILabel 子类化以重新定义前景(或使用第 3 方框架),这很烦人。
    • 在 iOS 6.0 及更高版本上,您可以将 UILabel 的属性文本设置为蓝色和下划线。
    • 为什么当我尝试在 ARC 中转换我的项目时,ARC 不允许将 'NSInteger'(又名 'int')隐式转换为 'UIEvent *'……它以前可以工作。我使用了你的代码 id hitLabel = [self.view hitTest:[rec locationInView:self.view] withEvent:UIEventTypeTouches];
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2015-01-19
        • 2013-02-06
        • 2012-12-15
        相关资源
        最近更新 更多