iOS实现一段文字中指定的某些文字点击有响应事件或者可以跳转(给字符串添加超链接)

直接上需求,见如下UI图:

需求是点击中间的电话(蓝色字体部分),可以直接拨打电话。对于这种很长的一段文字中间夹着可以有点击事件的文字,可以通过下面这种方式解决:

图中所指的这段文字,不用UILabel来展示,用UITextView来展示,如下:

//富文本
- (UITextView *)bottomTextView {
    if (!_bottomTextView) {
        _bottomTextView = [[UITextView alloc] init];
        _bottomTextView.backgroundColor = [UIColor clearColor];
        _bottomTextView.editable = NO;//设置为不可编辑
        _bottomTextView.scrollEnabled = NO;
        _bottomTextView.delegate = self;//设置代理
        _bottomTextView.textContainerInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);//控制距离上下左右的边距
        NSString *htmlString = [NSString stringWithFormat:@"<span style='color: #999999;'>放款时将以消息中心和短信通知您,实际到账时间依赖收款卡银行处理时间,请注意查收。如果您确认借款一天后仍未收到放款,您可以致电<a href='https://www.baidu.com' style='color: #007aff; text-decoration: none'> 400-060-8588 </a>咨询放款进度<span>"];
        //HTML格式的文本
        NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        NSMutableParagraphStyle *style = [attributedString attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil];
        style.alignment = NSTextAlignmentLeft;
        _bottomTextView.attributedText = attributedString;
    }
    return _bottomTextView;
}

这种方案其实利用的就是UITextView可以展示HTML格式的文本,如代码中的htmlString的值就是拼接的html文本,文本中可以设置点击的链接地址。点击链接会调用UITextView的下面这个代理方法:

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    
    //URL:就是那个跳转链接

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%ld",(long)4000608588]]];
    
    //返回NO,如果返回YES就会跳到Safari
    return NO;
}

注意:

1、UITextView上下左右默认是有间距的,可以通过textContainerInset属性来调整。

2、带链接的字体颜色默认是蓝色,在HTML文本中设置其他颜色是不生效的,如果想设置带链接的字体颜色可以通过UITextView的linkTextAttributes属性来设置。

发布了89 篇原创文章 · 获赞 92 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/u013602835/article/details/86691153
今日推荐