NSMutableAttributedString iOS 在UILabel显示不同的字体和颜色(转)

在项目开发中,我们经常会遇到在这样一种情形:在一个UILabel 使用不同的颜色或不同的字体来体现字符串,在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和 NSMutableAttributedText 类来实现。

现实代码:


@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UILabel *attrLabel;
- (IBAction)next:(id)sender;
@end
 .m文件 在viewDidLoad方法中添加以下代码:


self.title = @"For iOS 6 & later";
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];
attrLabel.attributedText = str;
NSString *const NSForegroundColorAttributeName;//值为UIColor,字体颜色,默认为黑色。


NSString *const NSBackgroundColorAttributeName;//值为UIColor,字体背景色,默认没有。


NSString *const NSLigatureAttributeName;//值为整型NSNumber,连字属性,一般中文用不到,在英文中可能出现相邻字母连笔的情况。0为不连笔;1为默认连笔,也是默认值;2在ios 上不支持。


NSString *const NSKernAttributeName;//值为浮点数NSNumber,字距属性,默认值为0。


NSString *const NSStrikethroughStyleAttributeName;//值为整型NSNumber,可取值为


enum {


NSUnderlineStyleNone = 0×00,


NSUnderlineStyleSingle = 0×01,


};设置删除线。


NSString *const NSUnderlineStyleAttributeName;//同上。设置下划线。


NSString *const NSStrokeColorAttributeName;//值为UIColor,默认值为nil,设置的属性同ForegroundColor。


NSString *const NSStrokeWidthAttributeName;//值为浮点数NSNumber。设置比画的粗细。


NSString *const NSShadowAttributeName;//值为NSShadow,设置比画的阴影,默认值为nil。


NSString *const NSVerticalGlyphFormAttributeName;//值为整型NSNumber,0为水平排版的字,1为垂直排版的字。

 

posted @ 2015-05-13 17:28  爱生活爱代码  阅读(1960)  评论(0编辑  收藏  举报