美文网首页
给字符串中的链接添加颜色及下划线

给字符串中的链接添加颜色及下划线

作者: 叫我小哥哥 | 来源:发表于2022-10-25 17:58 被阅读0次
// 给字符串中的链接添加颜色及下划线 关键点在与 NSTextCheckingTypeLink 
-(NSAttributedString *) attributedString:(NSString *)text {

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text];

    NSError *error;

    NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];

    NSArray *arrayOfAllMatches = [dataDetector matchesInString:text options:NSMatchingReportProgress range:NSMakeRange(0, text.length)];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches) {
         // 下划线颜色
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor cyanColor] range:match.range];
        [string addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:match.range];
    }
}

相关文章

网友评论

      本文标题:给字符串中的链接添加颜色及下划线

      本文链接:https://www.haomeiwen.com/subject/dntzzrtx.html