UILabel.numberOfLines = 2 but text diplays on 1 line

Has anyone had an issue before where UILabel.numberOfLines = 2 but the text displays on 1 line?


Any help is appreciated!

Does the text fit on one line or not ?


How did you set the wrapping options?

word wrapping as the option. Yes it all fits on one line.

So, it it fits on one line, no reason to use the second line.


To check if it is working, either make the text of the label much longer or reduce the witdth of the label and see if text wraps on a second line.

Actually sorry the issue lies here. This function is returning 2 but the text displays on 1 line.


func numberOfLinesForString(_ string: String, size: CGSize, font: UIFont) -> Int {

let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])


let textContainer = NSTextContainer(size: size)

textContainer.lineBreakMode = .byWordWrapping

textContainer.maximumNumberOfLines = 0

textContainer.lineFragmentPadding = 0


let layoutManager = NSLayoutManager()

layoutManager.textStorage = textStorage

layoutManager.addTextContainer(textContainer)


var numberOfLines = 0

var index = 0

var lineRange : NSRange = NSMakeRange(0, 0)

while (index < layoutManager.numberOfGlyphs ){

layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)

index = NSMaxRange(lineRange)

numberOfLines += 1

}

return numberOfLines

}


for reference:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html

Of course, I suppose font and size are the same in bith the func call and in the UILabel ?


I do not see in func numberOfLinesForString, where do you refernce the UILabel

If it fits on one line then it will print on one line. Add a carriage return "\n" to the text or add an alt-enter in the XIB entry.

I pass into the function the size of the UIlabel and according to the output I set the height of the UIlabel.


Oddly on the storyboard a particular sentence will display on 2 lines. The same sentence passed into the function will return 2 lines (as expected) but it will still be displayed on one line when the app runs.

Turns out the issue came from the custom font I was using. I had to adjust the width in order to account for that.

Thank you all for helping me out!

UILabel.numberOfLines = 2 but text diplays on 1 line
 
 
Q