在下面的代码中,我从字符串中检测 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);
}
}
答案 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
}