Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C label line spacing?

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.

like image 269
Secondwave Avatar asked Apr 19 '17 14:04

Secondwave


People also ask

How do I change line spacing in UILabel?

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels." This is a really old answer, and other have already addded the new and better way to handle this..

What is line height IOS?

The height, in points, of text lines.

What is UILabel?

A view that displays one or more lines of informational text.

How do I change the line height in SwiftUI?

SwiftUI text does not provide a lineHeight property (line spacing is a different beast). You could try to align the 'firstTextBaseLine' to get the desired behaviour. Alternatively, use a 'UILabel' (via 'UIViewRepresentable') with an attributed string (specify line height in the paragraph style).


2 Answers

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;
like image 191
Sargis Avatar answered Oct 15 '22 20:10

Sargis


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:

like image 45
Sid Mhatre Avatar answered Oct 15 '22 21:10

Sid Mhatre