iOS实用技能之同一个String不同颜色的字

前言

最近在开发中碰到个问题,需要一个字符串的数字为红色,其余为黑色。思考了半天,没思路,问了下同事,才了解到有AttributeString这个东西,看来我还是个新手啊,在这里做个记录,方便查阅吧。

要达到效果,比如 –> 这样数字8 红色的需求就可以用NSMutableAttributedString来实现。

废话不多说,直接上代码

//这里只是示例,你要求出需要设置颜色的字符的数量,这里为colorCount
NSInteger colorStrCount = 1;
        NSString *tempString = [NSString stringWithFormat:@"这里有:5人"];
        //用tempString来初始化一个NSMutableAttributedString
        NSMutableAttributedString *colorString = [[NSMutableAttributedString alloc]initWithString:tempString];
        //把colorString的4~colorStrCount这个范围内的字符设置为红色
        [colorString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, colorStrCount)];
        //注意,这里要用label的attributedText来接收,不能用text
        self.activityTimeleftLabel.attributedText = colorString;

这样写的效果就是 –> 这里有:5

猜你喜欢

转载自blog.csdn.net/koptop/article/details/52039995
今日推荐