2013-07-24 35 views
0

我想创建一个包含具有不同颜色文本的标签。与此类似,如何在iOS 5.1及更低版本的UILabel中创建多色文本

enter image description here

我已经在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中实现相同的结果。

+0

使用属性字符串http://www.cocoanetics.com/2011/01/befriending-core-text/! – rptwsthi

回答

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;` 
+0

使用此链接https://github.com/AliSoftware/OHAttributedLabel –

0

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

从的UILabel:

@property(nonatomic, copy) NSAttributedString *attributedText; 

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

追加块具有相同属性 - 每个零件创建一个NSAttributedString实例,并把它们添加到一个NSMutableAttributedString

创建一个从普通字符串属性文本,然后添加归结为给定的范围 - 找到你的号码(或其他)的范围,并在其上应用不同的颜色属性。

相关问题