15

How do I use auto-layout to make a child view fill its parent, or at least anchor all its edges to the parent view's edges?

I am using all four vertical and horizontal constraints in "Spacing to nearest neighbour", but when I run the app on a 3.5" device, the height of the view has not been automatically adjusted from 568 to 480 as expected.

Steve
  • 8,066
  • 11
  • 70
  • 112
  • Can you show us the constraints you've set up in IB? Most likely the "nearest neighbour" is not the view you're hoping it is, or your superview is not being correctly sized. – Jesse Rusak May 24 '14 at 16:26

2 Answers2

24

Pin the top space to superview, bottom space to superview, leading space to superview and trailing space to superview.

Pin

Then set edit the constraints like so:

Superview.Top >= View.Top and Superview.Bottom >= View.Bottom

67cherries
  • 6,931
  • 7
  • 35
  • 51
  • OK, I did it this way instead of pressing the pin button in the interface builder. The constraints appear to be different, but the result is the same. That is, the height of the view is still 568. Interestingly, when I add these constraints they seem to be added to the parent view rather than the selected view. Could be an IB bug. – Steve May 24 '14 at 16:38
  • Have you removed the original constraints? Maybe you should try to add the constraints again. – 67cherries May 24 '14 at 16:48
  • Yes I did. I'm quite clear about that because I'm using the document outline in interface builder. – Steve May 24 '14 at 16:50
  • When you applied the constraints was the subview filling the superview as desired? It has to be in order to work properly. – 67cherries May 24 '14 at 16:52
  • Sorry, I don't understand the question. What do you mean by "applied the constraints" and "subview filling the superview"? The subview *is* the same size as its superview in the interface builder, if that's what you mean. – Steve May 24 '14 at 16:55
  • Yes, that is what I meant. – 67cherries May 24 '14 at 16:58
  • I played around with these constraints that you suggested. In the constraints' inspector, I changed the top one to Superview.Top >= View.Top and Superview.Bottom >= View.Bottom. That seems to have done it. I don't know why, but it works. – Steve May 24 '14 at 16:59
  • Feel free to edit the answer with the information I provided in my last comment, then I will accept it. – Steve May 24 '14 at 17:03
  • There is no pin menu in XCode 7. Instead you need to click the pin icon at the bottom of the canvas. https://developer.apple.com/library/ios/recipes/xcode_help-IB_auto_layout/chapters/pin-constraints.html – CpnCrunch Aug 17 '16 at 18:36
4

I would just set all "Spacing to nearest neighbor" to 0, and align horizontal and vertical center. That should do the trick.

Anfaje
  • 335
  • 4
  • 14