3.同时设置: 行间距 与 字间距
//传入需要设置的 Label 与需要设置的行间距数值与字间距数值
+ (void)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace {
NSString *labelText = label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpace];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText = attributedString;
[label sizeToFit];
}
使用示例
//设置label内容,将lable内容变为有间距的内容
testLabel.text = @"测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字测试文字";
[UILabel changeLineSpaceForLabel:testLabel WithSpace:20];//设置testLabel中内容的行间距为20
[UILabel changeWordSpaceForLabel:self.testLabel WithSpace:20];//设置testLabel中内容的字间距为20
//
[UILabel changeLineSpaceForLabel:self.testLabel WithSpace:20];//设置testLabel中内容的行间距为20,字间距为20

计算Label富文字高度
计算思路
可以直接计算富字体排布高度,该高度即为 Label 高度,也可以使用 UILable 的方法来计算 Label 高度
方法1.使用UILabel方法:sizeThatFits
- (CGRect)sizeThatFits:(CGSize)size;
通过UILabel的方法sizeThatFits,该方法需要传入一个参数,即可算出目前label高度。
参数1. size:其中size的宽度为label的宽度,size的一般填入最大高度。
CGSize size = [label sizeThatFits:CGSizeMake(label.frame.size.width, CGFLOAT_MAX)];
方法2.使用NSString方法:boundingWithRect
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
context:(nullable NSStringDrawingContext *)context;
该方法需要传入3个参数:
参数1. size:其中size的宽度为label的宽度,size的一般填入最大高度。
参数2. options: 文本绘制时的附加选项
1. NSStringDrawingUsesLineFragmentOrigin (整个文本将以每行组成的矩形为单位计算整个文本的尺寸 )
2. NSStringDrawingUsesFontLeading (使用字体的行间距来计算文本占用的范围,即每一行的底部到下一行的底部的距离计算 )










