利用NSMutableAttributedString实现label上字体大小颜色行间距的改变

时间:2023-03-09 13:07:47
利用NSMutableAttributedString实现label上字体大小颜色行间距的改变

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

//     使用斜杠n是字体显示为两行

label.text = @"随堂测验\n(学习完成后,开始测试)";

label.font =  [UIFont systemFontOfSize:10];

//     使用换行符号切莫忘记写这句

label.numberOfLines = 0;

label.textColor = [UIColor hexChangeFloat:@"A5A5A5"];

//        利用属性字符串修改字体大小  颜色

NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc] initWithString:label.text];

[AttributedStr addAttribute:NSForegroundColorAttributeName

value:[HuConfigration uiColorFromString:@"#D3D3D3"]

range:NSMakeRange(0, 4)];

[AttributedStr addAttribute:NSFontAttributeName

value:[UIFont customFontSize:18]

range:NSMakeRange(0 , 4)];

//        修改行间距

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];

[paragraphStyle setLineSpacing:4];

[AttributedStr addAttribute:NSParagraphStyleAttributeName

value:paragraphStyle

range:NSMakeRange(0, [label.text length])];

label.attributedText = AttributedStr;

label.textAlignment = NSTextAlignmentCenter;

[self addSubview:label];

效果图:

利用NSMutableAttributedString实现label上字体大小颜色行间距的改变