*在开发时,有时需要在同一个label中设置不同大小、不同颜色的文字,下面就对这种情况介绍一下具体解决办法
一、显示效果
二、原理说明
UILabel有一个属性是 attributedText
*注意这个属性的注释,如果添加 attributedText 后,上面的其它属性将会被忽略,也就是 text、font、textColor、shadowColor、shadowOffset、textAlignment、lineBreakMode
如需要设置这些属性、需要在添加attributedText后设置。
三、代码
NSMutableAttributedString
是可以通过
range
设置多种颜色和字体大小的,这里通过UILabel 和
NSMutableAttributedString
一起使用达到在同一个label中显示不同颜色和字体的文字。
1、NSMutableAttributedString设置颜色方法:
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:NSMakeRange(1, 1)];
2、NSMutableAttributedString设置字体方法:
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 1)];
3、NSMutableAttributedString设置行间距方法:
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
[paragraphStyle setLineSpacing:20];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
4、下面是具体例子
-(void)addColorFulLabel
{
UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds];
label.center = self.view.center;
[self.view addSubview:label];
NSArray *colorNames = @[@"红色",@"橙色",@"黄色",@"绿色",@"蓝色",@"\n这是一个有意思的UILabel"];
//预设颜色
NSArray *colors = @[[UIColor redColor],[UIColor orangeColor],[UIColor yellowColor],[UIColor greenColor],[UIColor blueColor],[UIColor blackColor]];
//预设字体大小
NSArray *fonts = @[[UIFont systemFontOfSize:20],[UIFont systemFontOfSize:30],[UIFont systemFontOfSize:20],[UIFont systemFontOfSize:30],[UIFont systemFontOfSize:20],[UIFont systemFontOfSize:15]];
//创建 NSString
NSString *string = @"";
for (NSString *name in colorNames) {
string = [string stringByAppendingString:name];
if ([name isEqualToString:colorNames.lastObject]) {break;}
string = [string stringByAppendingString:@"/"];
}
//创建 NSMutableAttributedString
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:string];
NSArray *arr = [string componentsSeparatedByString:@"/"];
for (NSInteger i = 0; i<arr.count; i++) {
NSRange range = [string rangeOfString:arr[i]];
/**
设置字体/颜色(简单的设置大小、颜色通过这两行代码即可)
*/
[attributedString addAttribute:NSFontAttributeName value:fonts[i] range:range];
[attributedString addAttribute:NSForegroundColorAttributeName value:colors[i] range:range];
}
//行间距:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:20];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
label.attributedText = attributedString;
//设置居中需要在添加attributedText设置
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 2;
}