需求上需要在一个Label上显示不同的字体和颜色,可以设置其attributedText
1.建议创建一个类添加该方法,可根据业务需求自己定制该方法
- (NSString *)isNullOrEmpty:(NSString*)str
{
if ([str isKindOfClass:[NSNull class]] || str == nil || [str isEqualToString:@""]) {
return @"";
}
return str;
}
-(NSMutableAttributedString *)firstString:(NSString *)firstString firstColor:(UIColor *)firstColor secondString:(NSString *)secondString secondColor:(UIColor *)secondColor{
// 创建 firstAttributedString
NSMutableAttributedString * firstAttributedString = [[NSMutableAttributedString alloc] initWithString:[self isNullOrEmpty:firstString]];
// 设置 firstAttributes 属性 (字体、颜色)
NSDictionary * firstAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:firstColor};
// 设置 firstAttributedString 长度范围
[firstAttributedString setAttributes:firstAttributes range:NSMakeRange(0,firstAttributedString.length)];
// 创建 secondAttributedString
NSMutableAttributedString * secondAttributedString = [[NSMutableAttributedString alloc] initWithString:[self isNullOrEmpty:secondString]];
// 设置 secondAttributes 属性 (字体、颜色)
NSDictionary * secondAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:30],NSForegroundColorAttributeName:secondColor};
// 设置 secondAttributedString 长度范围
[secondAttributedString setAttributes:secondAttributes range:NSMakeRange(0,secondAttributedString.length)];
// 将两个firstAttributedString 和 secondAttributedString 进行字符串拼接
[firstAttributedString appendAttributedString:secondAttributedString];
// 返回字符串
return firstAttributedString;
}
2.调用方法显示在Label上
self.testLabel.attributedText = [self firstString:@"aaaaa" firstColor:[UIColor redColor] secondString:@"bbbbbbb" secondColor:[UIColor blueColor]];
展示效果: