1.创建UILabel的类别,为什么创建类别不做继承,因为不想影响label,哈哈
2.声明类方法:
/**
* 改变行间距
*/
+ (void)changeLineSpaceForLabel:(UILabel*)label WithSpace:(float)space;
/**
* 改变字间距
*/
+ (void)changeWordSpaceForLabel:(UILabel*)label WithSpace:(float)space;
/**
* 改变行间距和字间距
*/
+ (void)changeSpaceForLabel:(UILabel*)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace;
3.实现类方法
/**
改变label的行间距
*/
+ (void)changeLineSpaceForLabel:(UILabel*)label WithSpace:(float)space {
NSString*labelText = label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStylesetLineSpacing:space];
[attributedStringaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText= attributedString;
[labelsizeToFit];
}
/**
* 改变字间距
*/
+ (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];
[attributedStringaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText= attributedString;
[labelsizeToFit];
}
//改变行间距和字间距
+ (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];
[paragraphStylesetLineSpacing:lineSpace];
[attributedStringaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText= attributedString;
[labelsizeToFit];
}
4.需要注意的是,一定要确保调用方法的label的text不是空!!