使用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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值