藤原とうふ店(自家用)

iOS - UITextView实现富文本,并自定义可点击的富文

2023-05-23  本文已影响0人  温柔vs先生
UITextView *textView = [[UITextView alloc] init];
    textView.userInteractionEnabled = YES;
    textView.font = [UIFont systemFontOfSize:12];
    textView.textColor = hexColor(989898);
    textView.delegate = self;
    textView.backgroundColor=[UIColor clearColor];
    textView.editable = NO;//必须禁止输入,否则点击将弹出输入键盘
    textView.scrollEnabled = NO;
    textView.textContainerInset = UIEdgeInsetsZero;
    textView.contentInset= UIEdgeInsetsZero;
    [self.view addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-5);
        make.left.offset(45);
        make.right.offset(-27);
        make.height.offset(50);
    }];
    [self settextView:textView];
- (void)settextView:(UITextView *)textView {
    NSMutableAttributedString *diffString = [[NSMutableAttributedString alloc] initWithString:@"By continuing, I confirm that I have reviewed and agree to the Service Agreement and the Privacy Policy."  attributes:@{
        NSForegroundColorAttributeName: hexColor(989898),
        NSFontAttributeName: [UIFont systemFontOfSize:12]
    }];
    [diffString addAttribute:NSLinkAttributeName
                       value:@"delegate://"
                       range:[[diffString string] rangeOfString:[NSString stringWithFormat:@"%@",@" Service Agreement "]]];/// 《用户协议》
    [diffString addAttribute:NSLinkAttributeName
                       value:@"privacy://"
                       range:[[diffString string] rangeOfString:[NSString stringWithFormat:@"%@",@" Privacy Policy"]]];/// 隐私政策》
    textView.linkTextAttributes = @{NSForegroundColorAttributeName: main_color};
    textView.attributedText = diffString;
    
}

代理

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction API_AVAILABLE(ios(10.0)) {
    
    /// 隐私
    if ([[URL scheme] isEqualToString:@"privacy"]){
        /// 跳转隐私政策界面
        
        NSLog(@"跳转隐私政策界面");
        [self pushWebView:TY_YINSI title:@"privacy policy"];
    }
    /// 协议
    else if ([[URL scheme] isEqualToString:@"delegate"]) {
        /// 跳转用户协议界面
        
        NSLog(@"跳转用户协议界面");
        [self pushWebView:TY_XIEYI title:@"Service Agreement"];
    }
    return YES;
}
上一篇下一篇

猜你喜欢

热点阅读