Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the UILabel height dynamically [duplicate]

Tags:

I have the following code:

label.numberOfLines = 0; // allows label to have as many lines as needed label.text = @"some long text"; [label sizeToFit]; 

How do I get the height of label in points?

like image 210
cdub Avatar asked Dec 09 '14 08:12

cdub


2 Answers

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.

like image 84
Fabio Berger Avatar answered Sep 30 '22 21:09

Fabio Berger


Use following method to calculate dynamic UILabel height:

- (CGFloat)getLabelHeight:(UILabel*)label {     CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);     CGSize size;      NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];     CGSize boundingBox = [label.text boundingRectWithSize:constraint                                                   options:NSStringDrawingUsesLineFragmentOrigin                                                attributes:@{NSFontAttributeName:label.font}                                                   context:context].size;      size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));      return size.height; } 
like image 38
Salman Zaidi Avatar answered Sep 30 '22 20:09

Salman Zaidi