Home > Net >  Stack view goes off the screen with constraints
Stack view goes off the screen with constraints

Time:12-29

I have vertical stack view with multiple hirozontal stack view's inside and i can't figure it out how to set constraints for them so their height and width would be "dynamic" (depending on a horizontal stack count).

Vertical stack should be full screen on all device's so it's constraints are 20:20:20:20 Buttons should be 1:1 aspect ratio

Even tho i set constraints for vertical stack view it goes off the screen for some reason.

Storyboard

Horizontal stack view:

Horizontal stack settings

Vertical stack view:

Vertical stack settings

CodePudding user response:

Your constraints are too strong. You are saying that the vertical stack view's 4 edges should be equal to the superview's 4 edges ( some constant), and without distorting any of the images, and all the images have to be the same width, with a spacing of 10 between them. That's not possible.

What you are seeing here is the layout system's attempt to satisfy the constraint that the leading and trailing edge of the vertical stack view should be equal to the superview's leading and trailing edge. However, this makes the images too big, which means that the total height becomes too large to fit on the screen, breaking the top and bottom edge constraints. If we try to satisfy the top and bottom edge constraints, the images need to be smaller, and we end up breaking the leading and trailing edge constraints.

What you meant to say is that the 4 edges of the vertical stack view should not exceed the 4 edges of the superview, right? That's a "less than or equal" or "greater than or equal" relationship, not "equal".

You should add:

  • stack view leading ≥ super view leading
  • stack view trailing ≤ super view trailing
  • stack view top ≥ super view top
  • stack view bottom ≤ super view bottom

However, just those four are not enough to determine the exact position of the vertical stack view. You still need some equality constraints.

Since you seem to want this to be horizontally centred, you should add a centerX constraint on the stack view. The images may not always be large enough to fill the bottom, so make the bottom equality constraint have a lower priority. You can always delete the bottom constraint entirely, but that will make the image not expand to fill the bottom space, even when it can. It seems like you want the images to always start at the top, so the top constraint can stay unchanged. The leading and trailing constraints are not needed anymore, because the centerX constraint already determines the horizontal position of the stack view.

enter image description here

CodePudding user response:

Try this:

Change the distribution of Vertical Stack View to Fill Equally.

Check this picture

  • Related