在使用富文本時(NSMutableAttributedString),看到都是固定的一堆字符串,而後去改變其中某幾個字符的顏色、大小等等,這些都還比較簡單,可是很大狀況下咱們得到的數據並非固定的,若是這時咱們想讓字體的顏色和大小隨着後臺返回數據的變化而變化,咱們應該怎麼作呢?思路同樣很簡單,就是得到咱們想要改變的字符,而後去賦值顏色和大小便可,不過因爲字符是動態的,在獲取該字符的range時再採用傳統的 NSRangeFromString()的方法已經獲取不到該range,因此致使部分童靴明明設置了顏色和大小卻並無什麼卵用而急得抓耳撓腮,那麼解決辦法來了,其實很簡單,只須要這樣作:字體
//得到想要改變字體顏色的range 在這裏 model.rule_action_desc是從後臺獲取到的數據,因爲「得到」字體和它相同,因此就拼到了一塊 NSRange range1 = [integralString rangeOfString:[NSString stringWithFormat:@"%@得到",model.rule_action_desc] options:NSBackwardsSearch];
這樣就得到了該range,看效果圖:code
再貼上個人富文本的代碼:orm
//從後臺獲取的字符串,加上定製的「得到」 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;