我正在使用 UILable 来显示数据。我有一个 NSString @“你好,你好吗?”。我想以不同的颜色显示每个单词。例如 Hello - 红色,How - 黄色等。
我尝试了很多,但我没有找到任何解决方案。有什么想法给任何人我怎样才能得到解决方案?
提前致谢。
只需使用:
- (IBAction)go:(id)sender {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words=[self.text.text componentsSeparatedByString:@" "];
NSArray *colors=[NSArray arrayWithObjects:[UIColor redColor],[UIColor grayColor],[UIColor blueColor],[UIColor blackColor],[UIColor purpleColor],nil];
for (NSString *word in words) {
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:colors[arc4random()%colors.count] range:range];
}
[self.text setAttributedText:string];
}
我会补充
YOURTEXTFIELD.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:18.0f];
或任何您想要的字体大小,因为如果用户按两次空格键(或有多个空格),上述功能将产生糟糕的结果。所以函数会变成:
代码:
- (IBAction)go:(id)sender {
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words=[self.text.text componentsSeparatedByString:@" "];
NSArray *colors=[NSArray arrayWithObjects:[UIColor redColor],[UIColor grayColor],[UIColor blueColor],[UIColor blackColor],[UIColor purpleColor],nil];
for (NSString *word in words) {
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:colors[arc4random()%colors.count] range:range];
YOURTEXTFIELD.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:18.0f];
}
[self.text setAttributedText:string];
YOURTEXTFIELD.font=[UIFont fontWithName:@"HelveticaNeue-UltraLight" size:18.0f];
}
尝试一下!