今天在项目中遇到需要设置较多文字的行间距问题,得到解决办法分享给大家。
下面贴出代码供参考:
1.正常使用
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 320, 200)];
[label setBackgroundColor:[UIColor blackColor]];
[label setFont:[UIFont systemFontOfSize:16]];
[label setTextColor:[UIColor whiteColor]];
label.text = @"文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距";
[label setNumberOfLines:0];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:8];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
label.attributedText = attributedString;
[self.view addSubview:label];
[label sizeToFit];
2.封装代码到辅助类
.h中:
#pragma mark - 设置UILabel行间距
+ (void)setLineSpacing:(CGFloat)lineSpacing withLabel:(UILabel *)label;
.m中:
#pragma mark - 设置UILabel行间距
+ (void)setLineSpacing:(CGFloat)lineSpacing withLabel:(UILabel *)label
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];
label.attributedText = attributedString;
[label sizeToFit];
}
使用:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 320, 200)];
[label setBackgroundColor:[UIColor blackColor]];
[label setFont:[UIFont systemFontOfSize:16]];
[label setTextColor:[UIColor whiteColor]];
label.text = @"文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距文字行间距.";
label.numberOfLines = 0;
[self.view addSubview:label];
//只需要调用一句代码即可
[UILabel setLineSpacing:10.f withLabel:label];
效果图:
转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/20394.html
微信打赏
支付宝打赏
感谢您对作者Alina的打赏,我们会更加努力! 如果您想成为作者,请点我