49

iOS UILabel添加行间距、字间距

 5 years ago
source link: http://www.cocoachina.com/ios/20181128/25625.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

写在前面

在实际开发中,Label的默认行间距大小一般都是满足不了UI设计师设计的行间距大小的。于是乎,就需要我们开发人员手动调整Label的行间距大小。

然而,UILabel并没有提供直接修改行间距大小的属性

但是我们可以用Label的attributedText属性来设置

先上效果图:

默认Label效果

bYJbqia.jpg!web

行间距效果

FRZbMzI.jpg!web

话不多说上代码:

NSString *str = @"在实际开发中,Label的默认行间距大小一般都是满足不了UI设计师设计的行间距大小的。于是乎,就需要我们开发人员手动调整Label的行间距大小。然而,UILabel并没有提供直接修改行间距大小的属性,但是我们可以用Label的attributedText属性来设置. 在实际开发中,Label的默认行间距大小一般都是满足不了UI设计师设计的行间距大小的。于是乎,就需要我们开发人员手动调整Label的行间距大小。然而,UILabel并没有提供直接修改行间距大小的属性,但是我们可以用Label的attributedText属性来设置";

NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 8.0; // 设置行间距
paragraphStyle.alignment = NSTextAlignmentJustified; //设置两端对齐显示
[attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedStr.length)];

UILabel *lineSpaceLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width - 40, 0)];
lineSpaceLabel.backgroundColor = [UIColor cyanColor];
lineSpaceLabel.numberOfLines = 0;
lineSpaceLabel.attributedText = attributedStr;
[lineSpaceLabel sizeToFit];
[self.view addSubview:lineSpaceLabel];

UITextView一样可以设置的哟

更新:我刚发布了文章就有人私信问怎么改变字间距 (每行字与字之间的间距)

其实很简单哟

加上这句代码就可以了

[attributedStr addAttribute:NSKernAttributeName value:@(10) range:NSMakeRange(0, attributedStr.length)];

效果如图:

Y7JFJb6.jpg!web

作者:陈_Chen

链接:https://www.jianshu.com/p/f4924b70a57e


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK