IOS开发-设置UILabel行间距lineSpacing

发布时间 2023-07-02 15:51:05作者: ZihangChu

1.如何设置UILabel行间距lineSpacing 

UILabel是没有这么一个直接暴露的属性的,想要修改lineSpacing,我们需要借助NSAttributedString来实现。

 NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.lineSpacing  = 15;
    NSMutableDictionary *attributes  = [NSMutableDictionary dictionary];
    [attributes setObject:style forKey:NSParagraphStyleAttributeName];
    label2.attributedText = [[NSAttributedString alloc] initWithString:label2.text attributes:attributes];

这样即设置了UILabel的行间距为15pt,但实际上的间距是大于10的

效果图:

 

我们需要在设置lineSpacing时,减去系统的自带边距:label2.font.lineHeight

   style.lineSpacing  = 15-(label2.font.lineHeight - label2.font.pointSize);

加上这行代码即可。

效果:

这样即可完美的设置UILable的行间距了。