有时候开发的时候为了看起来效果很好,产品会要求某一行的一段文字显示不一样的颜色
那么我们就要分开来写代码了。
如果是要求固定的位置变成什么颜色。比如显示的子为“点击注册按钮,即表示您已同意隐私条款和服务协议”我想要“注册”的字体变成红色其他的不变。
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;
写的不好的地方请指出。
谢谢!