Изменить цвет строки с помощью NSAttributedString?
у меня есть ползунок для опроса, который отображает следующие строки на основе значения ползунка: "очень плохо, Плохо, Хорошо, хорошо, очень хорошо".
вот код для слайдера:
- (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];
}
Я не понимаю, как использовать NSAttributedString чтобы сделать это.
6 ответов:
нет необходимости использовать
NSAttributedString. Все, что вам нужно, это простой ярлык с правильнымtextColor. Плюс это простое решение будет работать со всеми версиями iOS, а не только с iOS 6.а если вы напрасно хотите использовать
NSAttributedString, вы можете сделать что-то вроде этого: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;
Используйте что-то вроде этого (не проверено компилятором)
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text]; NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different NSArray *colors=@[[UIColor redColor], [UIColor redColor], [UIColor yellowColor], [UIColor greenColor] ]; [string addAttribute:NSForegroundColorAttributeName value:colors[sliderValue] range:range]; [self.scanLabel setAttributedText:texts[sliderValue]];
на Swift 4:
// Custom color let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1) // create the attributed colour let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor]; // create the attributed string let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor) // Set the label label.attributedText = attributedStringна Swift 3:
// Custom color let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1) // create the attributed color let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor]; // create the attributed string let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject]) // Set the label label.attributedText = attributedStringнаслаждайтесь.
на Swift 4:
var attributes = [NSAttributedStringKey: AnyObject]() attributes[.foregroundColor] = UIColor.red let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes) label.attributedText = attributedStringна Swift 3:
var attributes = [String: AnyObject]() attributes[NSForegroundColorAttributeName] = UIColor.red let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes) label.attributedText = attributedString
С Swift 4,
NSAttributedStringKeyимеет статическое свойство с именемforegroundColor.foregroundColorесть следующее объявление:static let foregroundColor: NSAttributedStringKeyзначение этого атрибута является
вы можете создать
NSAttributedStringNSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] }; NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];или
NSMutableAttributedStringприменить пользовательские атрибуты с диапазонамиNSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }]; [attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];Доступные Атрибуты: NSAttributedStringKey
Comments