iOS 字符串显示不同的颜色和字体


需求上需要在一个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]];

展示效果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值