0

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?

Ben Packard
  • 26,102
  • 25
  • 102
  • 183
  • You can get the resultant height pretty easily after layout is done, but why do you need to calculate the height prior to layout if you're using constraints? – Ben Jan 23 '15 at 02:25
  • I intend to use the view as a tableHeaderView. I am hoping to avoid the cycle of setting it without a frame and forcing a layout just to get the size, only to then apply that size and re-set the tableHeaderView. – Ben Packard Jan 23 '15 at 02:29
  • Specifically - http://stackoverflow.com/a/28102157/225253 – Ben Packard Jan 23 '15 at 02:36
  • Ah! Headers seem to be a big oversight in terms of Auto Layout, there's other tactics you can try (like with custom view and layoutSubviews) but don't know of anything simpler when it comes to table headers. – Ben Jan 23 '15 at 03:41

1 Answers1

1

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];
AdamPro13
  • 7,232
  • 2
  • 30
  • 28