// 1.创建要显示的字符串
NSString *str = @"hello iOS world";
// 2.将字符串拆分,按照需要展现的颜色或字体的不同拆分成多个单独的字符串,并转化成NSRange格式;
NSRange rangeA = [str rangeOfString:@"hello"];
NSRange rangeB = [str rangeOfString:@" iOS "];
NSRange rangeC = [str rangeOfString:@"world"];
// 3.将 1.中创建的字符串生成可自由设置的 NSMutableAttributedString
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:str];
// 4.给每一部分分别设置颜色
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:rangeA];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:rangeB];
[aStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rangeC];
// 5.分别设置字体
[aStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:25] range:rangeA];
[aStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:25] range:rangeB];
[aStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:25] range:rangeC];
// 6.创建label,设置label的显示文字,并添加到view上
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
label.attributedText = aStr;
[self.view addSubview:label];
效果图
网友评论