iOS设置UILabel文字的行间距和字间距

释放双眼,带上耳机,听听看~!
可以在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完成

人已赞赏
iOS文章

ios xib自定义,解决在导航栏不透明的情况下,自定义xib view高度被压缩64的问题

2020-5-20 20:23:12

iOS文章

iOS导航栏自定义view

2020-5-24 18:48:03

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索