How do I calculate the UILabel height dynamically [duplicate]

The easiest way to get the height is sizeThatFits. Use it like this:

Objective-C

CGFloat maxLabelWidth = 100;
CGSize neededSize = [label sizeThatFits:CGSizeMake(maxLabelWidth, CGFLOAT_MAX)];

Swift 3.0

let maxLabelWidth: CGFloat = 100
let neededSize = label.sizeThatFits(CGSize(width: maxLabelWidth, height: CGFloat.greatestFiniteMagnitude))

The height your label needs is neededSize.height.
Note that im using CGFLOAT_MAX for the size height, to make sure the label has enough place to fit in the CGSize.

The height of your label also depends on your width of the label, thats why I added maxLabelWidth, it makes a difference if the label can be 100pt wide or 200pt.

Hope this helps!

Edit:
Make sure you set label.numberOfLines = 0; otherwise neededSize returns the size where the text is in a single line.

Edit:
Added Swift version, although the naming is a bit weird, greatestFiniteMagnitude seems to be the correct equivalent for CGFLOAT_MAX.

Leave a Comment