iOS 点击文字识别超链接并实现跳转

7 篇文章 0 订阅

之前发过用原生方法写富文本加超链接的方法(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];
        }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值