iOS 富文本+点击事件

UITextView *agreementTextView = [[UITextView alloc] init];
    [self.agreementView addSubview:agreementTextView];
    [agreementTextView autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.agreementBtn];
    [agreementTextView autoAlignAxisToSuperviewMarginAxis:ALAxisHorizontal];
    agreementTextView.font = FONT_13;
    agreementTextView.text = agreementStr;
    agreementTextView.backgroundColor = [UIColor clearColor];
    agreementTextView.delegate=self;
    //必须禁止输入,否则点击将弹出输入键
    agreementTextView.editable=NO;
    agreementTextView.scrollEnabled=NO;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing= 1;
    NSDictionary*attributes = @{NSFontAttributeName:FONT_13,
                                NSParagraphStyleAttributeName:paragraphStyle};
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:agreementTextView.text attributes:attributes];
    [attributedString addAttribute:NSLinkAttributeName value:@"yonghuxieyi://" range:NSMakeRange(6,6)];
    [attributedString addAttribute:NSLinkAttributeName value:@"yisizhengce://" range:NSMakeRange(13,6)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:kColorWithRGBA(255, 255, 255, 0.5) range:NSMakeRange(0,agreementTextView.text.length)];
    agreementTextView.attributedText= attributedString;
    //设置被点击字体颜色
    agreementTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};

#pragma mark 富文本点击事件
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    if ([[URL scheme] isEqualToString:@"yonghuxieyi"]) {
        NSLog(@"富文本点击 用户协议");
        WebViewVC *vc = [[WebViewVC alloc] init];
        vc.url = [NSString stringWithFormat:@"%@%@", kApiBaseUrl, kAgreement];
        vc.title = kString(@"用户协议");
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([[URL scheme] isEqualToString:@"yisizhengce"]) {
        NSLog(@"富文本点击 隐私政策");
        WebViewVC *vc = [[WebViewVC alloc] init];
        vc.url = [NSString stringWithFormat:@"%@%@", kApiBaseUrl, kAgreement];
        vc.title = kString(@"隐私政策(暂无)");
        [self.navigationController pushViewController:vc animated:YES];
    }
    return YES;
}

效果图

截屏2020-09-03下午1.44.27.png

你可能感兴趣的:(iOS 富文本+点击事件)