改变Label不同的字显示不同的颜色

有时候开发的时候为了看起来效果很好,产品会要求某一行的一段文字显示不一样的颜色如图“注册”颜色为红色,其他的为黑色

那么我们就要分开来写代码了。

如果是要求固定的位置变成什么颜色。比如显示的子为“点击注册按钮,即表示您已同意隐私条款和服务协议”我想要“注册”的字体变成红色其他的不变。


 self.enterLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 200, 30)];
 self.enterLabel.textAlignment = NSTextAlignmentLeft;
 self.enterLabel.font = [UIFont systemFontOfSize:13];
 [self.view addSubview:self.enterLabel];

 NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:textStr];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,2)];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,2)];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(6,19)];
 self.enterLabel.attributedText = str;

这样的话”注册”字的颜色就会变成红色

也可以


    UILabel* noteLabel = [[UILabel alloc] init];
    noteLabel.frame = CGRectMake(60, 100, 250, 100);
    noteLabel.textColor = [UIColor blackColor];
    noteLabel.numberOfLines = 2;

    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"点击注册按钮,即表示您已同意隐私条款和服务协议"];
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@"注册"].location, [[noteStr string] rangeOfString:@"注册"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];

    NSRange redRangeTwo = NSMakeRange([[noteStr string] rangeOfString:@"条款"].location, [[noteStr string] rangeOfString:@"条款"].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:redRangeTwo];



    [noteLabel setAttributedText:noteStr];
    [noteLabel sizeToFit];
    [self.view addSubview:noteLabel];

看到的效果就是
这里写图片描述
这样就达到了目的了。

如果是判断里面的数字全变红色

      NSString *textStr = @"是23.0的非公开水电费562";

    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSString *temp = nil;

    for(int i =0; i < [textStr length]; i++)
    {
        temp = [textStr substringWithRange:NSMakeRange(i, 1)];
        NSScanner* scan = [NSScanner scannerWithString:temp];
        int val;

        if ( [scan scanInt:&val] && [scan isAtEnd]) {

            NSRange redRange = NSMakeRange(i, [[noteStr string] rangeOfString:temp].length);
            [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"67b440"] range:redRange];
        }
    }

    noteLabel.attributedText = noteStr;

写的不好的地方请指出。
谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值