Objective C label line spacing?

2019-03-31 00:17发布

Is there a way to set the distance of two lines within a UILabel? I tried to do it within Interface Builder but without success.

3条回答
Rolldiameter
2楼-- · 2019-03-31 00:48

You can use NSAttributedString to add spacing between two lines within a UILabel:

NSString *labelText = @"My String"; 
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:20];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;

OR

If you are using storyboard then you can control line spacing in the storyboard by selecting text type is attributed and add spacing value:

查看更多
姐就是有狂的资本
3楼-- · 2019-03-31 00:49

The code you want will be something like this:

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
    value:style
    range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;
查看更多
虎瘦雄心在
4楼-- · 2019-03-31 00:50

Since iOS 6, Apple added NSAttributedString to UIKit, making it possible to use NSParagraphStyle to change the line spacing.

Alternatively, you can do this via Storyboards using Attributed Text and then clicking the ... symbol. See link below for screenshot.

https://i.stack.imgur.com/aiNfR.png

查看更多
登录 后发表回答