我想创建一个包含不同颜色文本的标签。像这样,
我在 iOS 6 中使用 NSMutableAttributedString
完成了此操作
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: self.exerciseLbl.attributedText];
[text addAttribute: NSForegroundColorAttributeName value: [UIColor colorWithRed:(187/255.0) green:(57/255.0) blue:(38/255.0) alpha:1] range: NSMakeRange(0, 2)];
[self.exerciseLbl setAttributedText: text];
但这不适用于 iOS 5.1 及更低版本。那么我怎样才能在 iOS 5 中达到相同的结果。
最佳答案
/**(1)** Build the NSAttributedString *******/
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
// for those calls we don't specify a range so it affects the whole string
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
// now we only change the color of "Hello"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
/**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
myAttributedLabel.attributedText = attrStr;`
// Use the "Justified" alignment
`myAttributedLabel.textAlignment = UITextAlignmentJustify;`
关于iphone - 如何在 iOS 5.1 及更低版本的 UILabel 中创建多色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826547/