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

时间:2023-12-27 17:31:31

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

 #import "AppDelegate.h"

 @interface AppDelegate ()

 @end

 @implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
// 设置多属性字符串
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
// 设置蓝色字体,范围(0, 5),其中空格也算一个占位符
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(, )];
// 设置红色字体,范围(6, 12),其中空格也算一个占位符
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(, )];
// 设置红色字体,范围(13, 6),其中空格也算一个占位符
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(, )]; label.attributedText = str; [self.window addSubview:label];
[self.window makeKeyAndVisible];
return YES;
} @end