Wednesday, April 24, 2013

Why is my view disappearing in landscape orientation when using Autolayout?

Have you come across this particular scenario where you enable Autolayout, drag a view onto the parent view, change the orientation of the parent view to landscape and the view just disappears? If you rotate it back to portrait, the view comes back. I used to find this really confusing. There is a very logical explanation as to why this happens.

Here is my parent view with the view I dragged on to it.

Simple enough! You probably already know that the Autolayout feature uses constraints to figure out where a particular object is located within a view. So here is what the constraints look like for my view.

The parent view has a size of 320 x 460 in portrait mode which changes to 480 x 300 in landscape mode. So the reason for the disappearing view is quite simple.

When we have constraints for all sides of the view, it means that the child view will be resized automatically to meet those constraints regardless of what orientation it is in. The width of the child view is the width of the parent view minus the sum of the horizontal space constraints. Similarly, the height of the child view is the height of the parent view minus the sum of the vertical space constraints. In the portrait mode of this particular example, the child view has a width of 320 - (85 + 75) = 160, and a height of 460 - (95 + 205) = 160. And to verify that, all you have to do is select the child view and open up the size inspector and sure enough there it is.

Now let's see what happens when the view is rotated to landscape. As per our previous calculations the width of the rotated view should be 480 - (85 + 75) = 320 and the height of the new view will be 300 - (95 + 205) = 0. That's why you don't see the view in landscape, its height is zero. If you select the view in the document outline, you can see that the view has no height.

This problem occurs because we have 4 constraints describing how far away the child view should be from the 4 sides of the parent view and since those constraints are not flexible, the child view has to be resized to meet those constraints. If you want to see your child view in the same size even in the landscape mode, here is what you do.

1. Change the orientation to portrait and you can see your view.
2. Fix the width and height of your view by selecting the child view and selecting the menu option Editor->Pin->Width and Editor->Pin->Height.
3. Now that the height and width of your child view is fixed, remove the constraints for the bottom and right of the child view.

This is what the list of constraints looks like now:

Now rotate the view to landscape and voila your view is still visible.

No comments:

Post a Comment