之前发过用原生方法写富文本加超链接的方法(iOS富文本用法之UILabel怎么加载图片和超链接),但是缺陷是点击超链接没反应,因为label里面没有加点击手势。这次mark下一条带有网址的文字怎么实现点击跳转。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLink:)];
label.userInteractionEnabled = YES;
[label addGestureRecognizer:tap];
/*!
@brief 点击文本处理链接跳转
*/
-(void)clickLink:(UITapGestureRecognizer *)tap {
UILabel *label = (UILabel *)tap.view;
NSString *chatStr = label.text;
NSDataDetector *detector= [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *checkArr = [detector matchesInString:chatStr options:0 range:NSMakeRange(0, chatStr.length)];
//判断有没有链接
if(checkArr.count > 0) {
CommonWebVC *webVC = [[CommonWebVC alloc] init];
if (checkArr.count > 1) { //网址多于1个时让用户选择跳哪个链接
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择要打开的链接" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
for (NSTextCheckingResult *result in checkArr) {
NSString *urlStr = result.URL.absoluteString;
[alertController addAction:[UIAlertAction actionWithTitle:urlStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
webVC.webType = CommonWebTypeWebURL;
webVC.urlStr = urlStr;
[self.navigationController pushViewController:webVC animated:YES];
}]];
}
[self presentViewController:alertController animated:YES completion:nil];
}else {//一个链接直接打开
webVC.webType = CommonWebTypeWebURL;
webVC.urlStr = [checkArr[0] URL].absoluteString;
[self.navigationController pushViewController:webVC animated:YES];
}
}
}