在使用富文本时(NSMutableAttributedString),看到都是固定的一堆字符串,然后去改变其中某几个字符的颜色、大小等等,这些都还比较简单,但是很大情况下我们获得的数据并不是固定的,如果这时我们想让字体的颜色和大小随着后台返回数据的变化而变化,我们应该怎么做呢?思路一样很简单,就是获得我们想要改变的字符,然后去赋值颜色和大小即可,不过由于字符是动态的,在获取该字符的range时再采用传统的 NSRangeFromString()的方法已经获取不到该range,所以导致部分童靴明明设置了颜色和大小却并没有什么卵用而急得抓耳挠腮,那么解决办法来了,其实很简单,只需要这样做:
//获得想要改变字体颜色的range 在这里 model.rule_action_desc是从后台获取到的数据,由于“获得”字体和它相同,所以就拼到了一块
NSRange range1 = [integralString rangeOfString:[NSString stringWithFormat:@"%@获得",model.rule_action_desc] options:NSBackwardsSearch];
这样就获得了该range,看效果图:
再贴上我的富文本的代码:
//从后台获取的字符串,加上定制的“获得”
NSString *integralString = [NSString stringWithFormat:@"%@获得%@",model.rule_action_desc,model.rule_score];
//创建富文本
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:integralString];
//设置字体大小
[attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(0, attributedStr.string.length)];
//分别获得想要改变字体颜色的range
NSRange range1 = [integralString rangeOfString:[NSString stringWithFormat:@"%@获得",model.rule_action_desc] options:NSBackwardsSearch];
NSRange range2 = [integralString rangeOfString:[NSString stringWithFormat:@"%@",model.rule_score] options:NSBackwardsSearch];
//改变字体颜色
[attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x333333) range:range1];
[attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff4c79) range:range2];
UILabel *integralScoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(timeLabel.frame.origin.x + timeLabel.frame.size.width + 30, timeLabel.frame.origin.y, 120, timeLabel.frame.size.height)];
//设置label的attributedText
integralScoreLabel.attributedText = attributedStr;