0

我想创建一个标签,其中包含具有不同颜色的文本。像这样,

在此处输入图像描述

我在 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 中获得相同的结果。

4

3 回答 3

1
/**(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;`
于 2013-07-24T06:54:34.227 回答
0

对于低于 6 的 iOS,您可以继续使用https://github.com/AliSoftware/OHAttributedLabel。它提供了对我有用的类别和子类。我希望对你也有帮助。

于 2013-07-24T06:26:41.440 回答
0

从 iOS 6开始,UIKit 支持绘制属性字符串,因此不需要扩展或替换。

来自 UILabel:

@property(nonatomic, copy) NSAttributedString *attributedText;

你只需要建立你的 NSAttributedString。基本上有两种方式:

附加具有相同属性的文本块 - 为每个部分创建一个 NSAttributedString 实例并将它们附加到一个 NSMutableAttributedString

从纯字符串创建属性文本,然后为给定范围添加属性 - 找到您的数字(或其他)的范围并在其上应用不同的颜色属性。

于 2013-07-24T06:20:50.223 回答