有時候開發的時候爲了看起來效果很好,產品會要求某一行的一段文字顯示不一樣的顏色
那麼我們就要分開來寫代碼了。
如果是要求固定的位置變成什麼顏色。比如顯示的子爲“點擊註冊按鈕,即表示您已同意隱私條款和服務協議”我想要“註冊”的字體變成紅色其他的不變。
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;
寫的不好的地方請指出。
謝謝!