ios label文字行间距_iOS 设置UILabel行间距【原创】

本文分享了在iOS开发中设置UILabel文字行间距的方法,包括直接在代码中设置和封装到辅助类的两种方式,详细展示了如何通过NSMutableAttributedString和NSMutableParagraphStyle调整行间距。
摘要由CSDN通过智能技术生成

今天在项目中遇到需要设置较多文字的行间距问题,得到解决办法分享给大家。

下面贴出代码供参考:

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的打赏,我们会更加努力!    如果您想成为作者,请点我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值