由于标签是从开始显示的,文字的内容长度又不固定,图片的位置相对固定。
想实现这样的效果需要计算出文字和图片的总长度,通过设置分段文字颜色的富文本来实现:
-(void)setRank:(NSUInteger) rank { _rank = rank; UIColor *strokeColor = BGColorHex(C69116); NSUInteger tempRank = rank/10+1; if(0 == rank) { tempRank = 0; } else if(rank >= 100) { tempRank = 10; } switch (tempRank) { case 0: strokeColor = BGColorHex(A1A1A1); break; case 1: strokeColor = BGColorHex(FE7241); break; case 2: strokeColor = BGColorHex(FF9802); break; case 3: strokeColor = BGColorHex(FFBF01); break; case 4: strokeColor = BGColorHex(CBDC3C); break; case 5: strokeColor = BGColorHex(699E38); break; case 6: strokeColor = BGColorHex(26A99C); break; case 7: strokeColor = BGColorHex(05A8F3); break; case 8: strokeColor = BGColorHex(4F6BEA); break; case 9: strokeColor = BGColorHex(663CB5); break; case 10: strokeColor = BGColorHex(E9407B); break; default: break; } NSString *rankStr = [NSString stringWithFormat:@"%lu", rank]; NSString *str = [NSString stringWithFormat:@"fron%@", rankStr]; NSUInteger fillCharacterCount = 4; NSMutableAttributedString *textAttributedString = [[NSMutableAttributedString alloc] initWithString:str]; [textAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0, fillCharacterCount)]; [textAttributedString addAttribute:NSStrokeColorAttributeName value:strokeColor range:NSMakeRange(fillCharacterCount, rankStr.length)]; [textAttributedString addAttribute:NSStrokeWidthAttributeName value:@4.0 range:NSMakeRange(fillCharacterCount, rankStr.length)]; [textAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.f] range:NSMakeRange(0, fillCharacterCount)]; [textAttributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12.f] range:NSMakeRange(fillCharacterCount, rankStr.length)]; self.describeTitleLabel.attributedText = textAttributedString; [self.describeTitleLabel updateLayout]; textAttributedString = [[NSMutableAttributedString alloc] initWithString:str]; [textAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(0, fillCharacterCount)]; [textAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(fillCharacterCount, rankStr.length)]; [textAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.f] range:NSMakeRange(0, fillCharacterCount)]; [textAttributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12.f] range:NSMakeRange(fillCharacterCount, rankStr.length)]; self.underDescribeTitleLabel.attributedText = textAttributedString; [self.underDescribeTitleLabel updateLayout]; NSString *filename = [NSString stringWithFormat:@"lv%lu", tempRank]; self.decribeImageView.image = [UIImage imageNamed:filename]; }