Question

I am programming an iPad application that uses auto layout to correctly position views on the screen in both portrait and landscape orientation. The layout (simplified) looks like this:

-UIView
 -UIScrollView (all spacing pinned to superview)
  -UIView (top, bottom spacing pinned to superview, leading and trailing spacing pinned to root view to prevent horizontal scrolling)
   -UIImageView (leading and trailing spacing pinned to superview, height pinned to fixed value)
   -UILabel (leading, trailing, and top spacing pinned to superview)

I have got the ScrollView to work, but I want the UILabel to scale vertically to fit its multiline content, which is not working. It does adjust its height based on the content, but it uses the (fixed) frame width specified in the storyboard to do so, instead of the actual width that is calculated by using the constraints, which changes when the device changes orientation. This leads to the UILabel being too high in landscape mode. Since a UILabel's content is vertically centered, this makes the top margin of the text too large.

I have no idea what is causing the trouble. Trying to add a height constraint to the UILabel and then calculating the height programatically using [NSString sizeWithFont:constrainedToSize], but this resulted in the exact same problem (I was unable to get the correct width as input). How do I fix this?

Was it helpful?

Solution

Although the reason for the problems is still unclear to me, I fixed the problem by subclassing UILabel and putting the following code:

@implementation MyLabel

- (void)layoutSubviews
{
    self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
    [super layoutSubviews];
}

@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top