ios - textview实现点击文字位置识别

1.创建textView
UITextView *protocolButton = [[UITextView alloc] init];
    [self.view addSubview:protocolButton];
    self.textView = protocolButton;
    protocolButton.textColor = [UIColor colorWithHexString:@"c0c0c0"];
    protocolButton.font = kFont(12);
    protocolButton.delegate = self;
    protocolButton.editable = NO;
    protocolButton.scrollEnabled = NO;
    //    protocolButton.selectable = NO;// 禁止粘贴复制
    
    [protocolButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(bottom);
        make.width.mas_equalTo(KScreenWidth - 20);
        make.height.mas_equalTo(44);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    NSString *str1 = @"《用户个人信息保护政策》";
    NSString *str2 = @"《用户协议与隐私条款》";
    
    NSString *str = @"登录即表示你同意《用户个人信息保护政策》和《用户协议与隐私条款》";
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str];
    
    [string addAttribute:NSLinkAttributeName value:@"https://www.jianshu.com/u/48c3fd8a4c7e" range:[str rangeOfString:str1]];
    [string addAttribute:NSLinkAttributeName value:@"https://www.jianshu.com/u/48c3fd8a4c7e" range:[str rangeOfString:str2]];
    
    protocolButton.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor colorWithHexString:@"4dafea"],
                                           NSUnderlineColorAttributeName: [UIColor clearColor],
                                           NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    
    protocolButton.attributedText = string;
    
    [self.view addSubview:self.thirdLoginView];
    [self.thirdLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(73);
        make.bottom.equalTo(protocolButton.mas_top).offset(-20);
    }];

2.实现textView代理:

#pragma mark - 点击label文字识别跳转
//textview代理事件
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    if ([URL.scheme containsString:@"http"]) {
        JLXXProtocolWebController *webVC = [[JLXXProtocolWebController alloc]init];
        webVC.urlString = URL.absoluteString;
        [self.navigationController pushViewController:webVC animated:YES];
        return NO;
    }
    return YES;
}

推荐阅读更多精彩内容