Ben Packard
Ben Packard

Reputation: 26476

Is there a way to ask an AutoLayout constrained view for it's height?

If a UIView subclass is laid out programmatically using constraints, and it includes some multi-line labels, how can I calculate the required height for that view given some arbitrary width?

I am aware of the method systemLayoutSizeFittingSize: but these seems to expect something like UILayoutFittingCompressedSize rather than a specific width. How can it return an accurate height or width without me providing the other?

Upvotes: 0

Views: 56

Answers (1)

AdamPro13
AdamPro13

Reputation: 7400

As far as I know, you will need to calculate the size of each label individually. This should do the trick to calculate the size of a single multi-line label.

CGSize boundingRectSize = CGSizeMake(widthToConstrainTo, CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : [UIFont fontWithName:fontName size:fontSize]};
CGRect labelSize = [labelString boundingRectWithSize:boundingRectSize 
                                             options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                          attributes:attributes
                                             context:nil];

Upvotes: 1

Related Questions