将文本转换为超链接,分配给UILabel

时间:2014-05-12 13:05:32

标签: ios objective-c cocoa-touch

在下面的代码中,我从字符串中检测 url 。现在我只需要将超链接放到检测到的" url"每当我点击这个 url 时就分配到UILabel它应该转到浏览器,该怎么做?

代码:

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);
    }
}

4 个答案:

答案 0 :(得分:5)

您应该做的是在UITapGestureRecognizer上创建UILabel,当点击UILabel时,您应该打开网址。

创建这样的手势:

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

接下来按下时会写下此delegate方法:

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

答案 1 :(得分:0)

我的建议是,将链接放在按钮而不是标签上,因为标签没有自己的点击事件/操作,所以你需要使用点击手势在标签上应用可点击功能,其中按钮有自己的forControlEvents所以你可以轻松处理它。仍然是链接下划线的东西,然后把按钮的背景图像看起来像下划线。

URL转换为NSString

NSString *urlString = [myURL absoluteString];

否则您可以从 @Khawar Ali's 回答所有信息:)

答案 2 :(得分:0)

我的建议是,在背景视图中使用UIButton设置清晰颜色,并使用IBAction方法来管理打开URL的操作。

in .h

-(IBAction)openUrl:(id)sender; 

in .m

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

}

就像我们的朋友说的那样。

答案 3 :(得分:0)

试试这个:

 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
 }