UITextView增加超链接,配置不同的链接颜色

先看下效果是否是需要的那种:

UITextView增加超链接,配置不同的链接颜色_第1张图片
UITextView+link.png

如果是,直接上代码,简单粗暴。

// 构造一段文件以及链接
NSArray *array = @[@{@"text" : @"制药巨头默克公司申请区块链专利,旨在打击假药",
                         @"color" : [UIColor redColor],
                         @"link" : @"test1"
                         },
                       @{@"text" : @"区块链跨链机制的难点和解决方案",
                         @"color" : [UIColor orangeColor],
                         @"link" : @"test2"
                         },
                       @{@"text" : @"苹果品牌价值被亚马逊超越 依旧屈居第二位",
                         @"color" : [UIColor greenColor],
                         @"link" : @"test3"
                         }
                       ];
// 构造字符串
    NSMutableString *string = [[NSMutableString alloc] init];
    for (NSDictionary *dict in array) {
        [string appendFormat:@"加上%@", dict[@"text"]];
    }
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:string];
    [attr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, string.length)];
    [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, string.length)];
    
    for (NSUInteger i = 0; i < array.count; i++) {
        NSDictionary *dict = array[i];
        NSRange range = [string rangeOfString:dict[@"text"]];
        [attr addAttribute:NSLinkAttributeName
                     value:dict[@"link"]
                     range:range];
        [attr addAttribute:NSForegroundColorAttributeName value:dict[@"color"] range:range];
    }
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:3];
    [attr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, string.length)];
设置 textView
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 80, 200, 0)];
textView.scrollEnabled = NO;
textView.delegate = self;
textView.editable = NO;
textView.dataDetectorTypes = UIDataDetectorTypeAll;
textView.font = [UIFont systemFontOfSize:13];

// 这个不加的话颜色无法单独控制
textView.linkTextAttributes = @{};
textView.attributedText = attr;
[textView sizeToFit];
[self.view addSubview:textView];
    
// 这两行控制padding,看实际需求
textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsZero;

上述代码可以一起拷贝到viewdidload里,我把他分开是为了看起来清晰一点。

最后实现代理方法以响应点击:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    if ([URL.description isEqualToString:@"test1"]) {
        // do what you want
        NSLog(@"select test1");
    }
    return NO;
}

坑点:

sizeToFit之后,会发现高度计算有点问题,下面会多点,需要设置:

textView.scrollEnabled = YES;  

这里虽然设置为YES,但textView实际并不会滚动,并正确显示出来内容

你可能感兴趣的:(UITextView增加超链接,配置不同的链接颜色)