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

对于富媒体的文本,使用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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容