使用TTTAttributedLabel 添加可点击链接并且改变链接颜色

卜勇
2023-12-01

对于富媒体的文本,使用TTTAttributedLabel是一个不错的选择。
代码中有很多和我们自己业务相关的部分,请大家参考即可。

/**
 替换数据中的话题,把话题占位图替换成可点击的话题
 
 @param origialStr 原始字符串
 @param str        替换占位图的字符串
 
 @return 富媒体类型的字符串(因为替换的字符串是要可以点击的)
 */
+(TTTAttributedLabel *)replaceTopicWithContent:(NSString *)origialStr andReplaceString:(NSString *)str andIndex:(int)index andLabel:(TTTAttributedLabel *)label{

  TTTAttributedLabel * changeLabel = label;
//改变链接的颜色
    NSMutableDictionary *linkAttributes = [NSMutableDictionary dictionary];
//去掉下划线
    [linkAttributes setValue:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
//改变链接文字的颜色
    [linkAttributes setValue:(__bridge id)[UIColor redColor].CGColor forKey:(NSString *)kCTForegroundColorAttributeName];
    changeLabel.linkAttributes = linkAttributes;

    //设置要添加链接的文本
   //origialStr:原本的字符串
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:origialStr];
    NSRange range = [origialStr rangeOfString:[NSString stringWithFormat:@"<!--TOPIC#%d-->",index]];
    //替换
    if (range.length>0) {
       [string replaceCharactersInRange:range withString:[NSString stringWithFormat:@"#%@#",str]];
        [changeLabel setText:string];
        //添加可点击区域
        //设置可点击文字范围
        NSRange myRange = [[string string] rangeOfString:[NSString stringWithFormat:@"#%@#",str]];
        
        //添加链接,通过比较url中的话题名称区分是第几个话题
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"topic:%@",str]];
        [changeLabel addLinkToURL:url withRange:myRange];
    }
    
    return changeLabel;
}
 类似资料: