释放双眼,带上耳机,听听看~!
可以在UILabel的Category中提供如下几个方法:
.h文件
@interface UILabel (ChangeLineSpaceAndWordSpace)
/**
* 改变行间距
*/
+ (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space;
/**
* 改变字间距
*/
+ (void)changeWordSpaceForLabel:(UILabel *)label WithSpace:(float)space;
/**
* 改变行间距和字间距
*/
+ (void)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace;
@end
.m文件
@implementation UILabel (ChangeLineSpaceAndWordSpace)
+ (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
NSString *labelText = label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:space];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText = attributedString;
[label sizeToFit];
}
+ (void)changeWordSpaceForLabel:(UILabel *)label WithSpace:(float)space {
NSString *labelText = label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(space)}];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText = attributedString;
[label sizeToFit];
}
+ (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];
}
@end
附: 在Xcode8中创建Category文件的方法:
在工程目录中右键选择New File...或者使用键盘command+N, 然后在弹出窗口中选择Objective-C File
新建文件
然后
起名字, 选择Category, 并选择要扩展的类
最后
设置好后点击Next完成