我有一个用于调查的滑块,它根据滑块的值显示以下字符串:"Very Bad,Bad,of,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];
}
我希望“很坏”是红色的,“坏”是橙色的,“好”是黄色的,“好”和“非常好”是绿色的。
我不知道如何使用NSAttributedString
来完成这项工作。
发布于 2013-01-12 06:50:39
不需要使用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;
发布于 2013-01-12 06:07:12
使用类似这样的代码(不检查编译器)
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]];
发布于 2018-02-06 16:53:16
您可以创建NSAttributedString
NSDictionary *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)];
更新:
Swift 5.1
let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]
let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))
https://stackoverflow.com/questions/14287386
复制相似问题