UILable如何实现加载带链接的富文本,同时可以跳转

2023-12-20  本文已影响0人  爱的就是娜

这边的需求呢,就是文本中会出现带人名的特殊显示,而且点击人名能够拨打电话

我这弄了半天,发现使用lable弄了半天都没法实现这个,然后,我就用textView实现了,效果与lable没区别

// 初始化

self.noteTextView = [[UITextView alloc] init];

 self.noteTextView.backgroundColor = [UIColor clearColor];

            self.noteTextView.editable=NO;//设置为不可编辑

            self.noteTextView.scrollEnabled=NO;

            self.noteTextView.delegate=self;//设置代理(<UITextViewDelegate>)

            self.noteTextView.textContainerInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);//控制距离上下左右的边距

NSString * nameStr = @"张三";

 NSString * ownStr = [NSString stringWithFormat:@"<a href='tel://%@' style='color: #3D8777; text-decoration: none'>%@</a>",@"13311209976",@"张三"];

    NSMutableString * mutableStr = [NSMutableString stringWithString:@"张三想屁吃"];

[mutableStr replaceOccurrencesOfString:nameStr withString:ownStr options:NSLiteralSearch range:NSMakeRange(0, mutableStr.length)];

 //HTML格式的文本

    NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithData:[mutableStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];

    NSMutableParagraphStyle *style = [attributedString attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:nil];

    style.alignment = NSTextAlignmentLeft;

    self.noteTextView.attributedText= attributedString;

// 设置人名的颜色,默认为.a标签的蓝色

    self.noteTextView.linkTextAttributes = @{NSForegroundColorAttributeName:MainStyleColor};

// 代理方法

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView*)textViewshouldInteractWithURL:(NSURL*)URLinRange:(NSRange)characterRange {

    //URL:就是那个跳转链接

    NSString* abslutStr = URL.absoluteString;

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:abslutStr]];

//    NSString * phoneStr = [URL.absoluteString stringByReplacingOccurrencesOfString:@"tel://" withString:@""];

//    if(phoneStr.length) {

  //      [NRContactTool callNumber:phoneStr withPrompt:NO];

//    }

    //返回NO,如果返回YES就会跳到Safari

    return NO;

}

上一篇 下一篇

猜你喜欢

热点阅读