使用NSAttributedString更改字符串颜色? [英] Change string color with NSAttributedString?

查看:211
本文介绍了使用NSAttributedString更改字符串颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调查滑块,根据滑块的值显示以下字符串:很差,坏,好,好,很好。

I have a slider for a survey that display the following strings based on the value of the slider: "Very Bad, Bad, Okay, Good, Very Good".

以下是滑块的代码:

- (IBAction) sliderValueChanged:(UISlider *)sender {
    scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSArray *texts=[NSArray arrayWithObjects:@"Very Bad", @"Bad", @"Okay", @"Good", @"Very Good", @"Very Good", nil];
    NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
    self.scanLabel.text=[texts objectAtIndex:sliderValue];
}

我要非常差为红色,差 ,Okay为黄色,Good和Very Good为绿色。

I want "Very Bad" to be red, "Bad" to be orange, "Okay" to be yellow, "Good" and "Very Good" to be green.

我不明白如何使用 NSAttributedString 来完成这项工作。

I don't understand how to use NSAttributedString to get this done.

推荐答案

不需要使用 NSAttributedString 。所有你需要的是一个简单的标签与正确的 textColor 。此外,这个简单的解决方案将适用于所有版本的iOS,而不仅仅是iOS 6.

There is no need for using NSAttributedString. All you need is a simple label with the proper textColor. Plus this simple solution will work with all versions of iOS, not just iOS 6.

但如果你不必要地希望使用 NSAttributedString ,你可以这样做:

But if you needlessly wish to use NSAttributedString, you can do something like this:

UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;

这篇关于使用NSAttributedString更改字符串颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆