0

I'm using auto-layout with XCode 5 for iOS 7. I've set a UILabel with constraints for leading space to the superview (which is a UIScrollView), top space to an imageview, and bottom space to the superview which causes the label to resize based on content and dictates the scrollview's content size – which is perfect. However, whenever the device is rotated to portrait position, the UILabel expands in width (which I want) but no longer needs as much vertical space... the Bottom Space to Superview (eq: 81 pts) creates a UILabel that is too tall for it's content and without top vertical alignment centers the content vertically. Is there a way to automatically handle this or do I need to manually extend the bottom space to the superview on device rotation?

Interface Builder: http://cl.ly/image/2r1a3H1U2r0R ; http://cl.ly/image/2o2A3I44353a

Portrait: http://cl.ly/image/060p2Z0L3S0D

Landscape: http://cl.ly/image/360E1u1s0R1H

Jayson Lane
  • 2,828
  • 1
  • 24
  • 39

1 Answers1

2

Instead of setting the label's height (by setting its top and bottom), leave its height alone. The label's height will automatically increase or decrease as its width changes, in such a way as to fit its content perfectly.

EDIT: Ooops, failed to read the question carefully enough; we can't remove the bottom constraint, as it is needed to help set the size of the superview (the scroll view's content view). In that case, the solution is to prompt the label to assume the correct height for its content, by setting its self.preferredMaxLayoutWidth to match its width. Here's code from my book showing a UILabel subclass that automatically adjusts itself in this way:

-(void)layoutSubviews {
    [super layoutSubviews];
    self.preferredMaxLayoutWidth = self.bounds.size.width;
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • If I remove the bottom space to superview, it no longer forces the scrollview's contentview to expand and essentially gets clipped – Jayson Lane Jan 07 '14 at 17:11
  • 1
    During layout, set the label's `preferredMaxLayoutWidth` to match its width. This will force the label to assume the right height. – matt Jan 07 '14 at 17:14
  • I came to that solution after reading this answer: http://stackoverflow.com/a/19194592/535632 – Jayson Lane Jan 07 '14 at 17:14
  • See my book for code (the end of this section: http://www.apeth.com/iOSBook/ch23.html#_uilabel). Thank you for the checkmark; I don't deserve it, since I failed to read your question carefully enough. I will edit to improve my answer. – matt Jan 07 '14 at 17:38
  • actually your answer here about subclassing UILabel is the PERFECT solution to my problem: http://stackoverflow.com/a/13616052/535632 – Jayson Lane Jan 07 '14 at 17:42
  • 1
    Yes, I reproduced that code in the edit of my answer above. Glad you got this sorted! – matt Jan 07 '14 at 18:23