代码改变世界

在一个Label上设置多种颜色字体

2015-06-26 16:09  甘雨路  阅读(763)  评论(0编辑  收藏  举报

                                           

               

 1 #import "AppDelegate.h"
 2 
 3 @interface AppDelegate ()
 4 
 5 @end
 6 
 7 @implementation AppDelegate
 8 
 9 
10 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
11     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
12     
13     // Override point for customization after application launch.
14     self.window.backgroundColor = [UIColor whiteColor];
15     
16     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 200)];
17     // 设置多属性字符串
18     NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using   NSAttributed   String"];
19     // 设置蓝色字体,范围(0, 5),其中空格也算一个占位符
20     [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
21     // 设置红色字体,范围(6, 12),其中空格也算一个占位符
22     [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6, 12)];
23     // 设置红色字体,范围(13, 6),其中空格也算一个占位符
24     [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(13, 6)];
25     
26     label.attributedText = str;
27     
28     [self.window addSubview:label];
29     [self.window makeKeyAndVisible];
30     return YES;
31 }
32 
33 @end