2 yue1liang1chuan yue1liang1chuan 于 2013.01.14 16:30 提问

NSAttributedString修改字符串颜色

应用中有一个滚动条,根据滚动条的值显示下面的字符串:
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];
}

其中Very Bad红色,Bad橙色,Okay黄色,Good和Very Good绿色。不知道怎么设置attributedstring实现?谢谢

1个回答

xinyoulingxi1_tong
xinyoulingxi1_tong   2013.01.14 16:39
已采纳

我还没编译:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.text.text rangeOfString:[texts objectAtIndex:sliderValue]];

NSArray *colors=[NSArray arrayWithObjects:[UIColor redColor],[UIColor redColor],[UIColor yellowColor],[UIColor greenColor],nil];

[string addAttribute:NSForegroundColorAttributeName value:[colors objectAtIndex:sliderValue] range:range];           

[self.scanLabel setAttributedText:[texts objectAtIndex:sliderValue]];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!