Reputation: 1465
I have a UILabel
that I need to have a specific text size and frame width (matching the screen width). I want to be able to set the label's height to the minimum height that will fit all of the label's text without cutting it off.
I've tried the following:
let label = UILabel()
label.text = longText
label.numberOfLines = 0
label.sizeToFit()
But this won't work if longText
is something like "This string is really long, longer than the screen width"
as sizeToFit
puts that entire string on one line and the text gets cut off with ...
when it reaches the screen width.
I then tried setting the label's width to match the screen width after calling sizeToFit
. This lets the line wrap but doesn't adjust the label's height, so the string is still cut off after the first line.
Also, setting label.adjustsFontSizeToFitWidth = true
won't work because I need the label to have a specific font size.
What I'd like to have is some kind of function like label.minimumHeightForWidth:
where I can pass UIScreen.main.bounds.width
as the width parameter and get a height that will fit the label's text on as many lines as needed with the given width parameter. Is it possible to do something like this?
Upvotes: 0
Views: 153
Reputation: 100503
You can try
let fixedWidth = UIScreen.main.bounds.width
let newSize = lbl.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
lbl.size = CGSize(width:fixedWidth, height: newSize.height)
Upvotes: 2