I am trying to use a vertical stack view (Stack View 1) to fill an entire screen where the elements in the stack are a horizontal stack view with 2 labels (Stack View2), an image view, a text View, a horizontal stack view with buttons to add content (Stack View3), and then a collection view to view the files uploaded. In xCode preview, everything looks right. I set constraints that the Stack View 1 be set to the safe area at the top and to the view area for left right and bottom, I set Stack View2 to be 20 in height so my text wouldn’t clip, I set up constraints that the buttons in Stack View3 all be 40 by 40, and I set up constraints that the image view never bee more than 33% of the size of the view.
On Preview everything looks good…
But then when I load it up on simulator everything is all over the place… My expectation was that the I would always get 33% of screen for image and then after the 40+20 for the stack views the text view and collection view would fill out the rest of the space.
Can anyone provide any hints as to which constraints I missed or what settings on the stack view I may have incorrect? I know its hard to help with constraints on a board like this. But any hint for something I may be missing would be greatly appreciated. The main thing I am perplexed by is why stack view3 didn’t fill the 40×40 buttons correctly.
2
Answers
The first thing I’d check is whether
stackView3
has its distribution set to beequalSpacing
.Next I’d double check the image constraint is how you described it to be, it’s cut off in your image so we cant tell if it’s correct. If it’s using an inequality constant you could temporarily change it to use equality and see if that improves things.
If it’s neitth of those, I’d suspect the stack view is adding its own constraint into one of the buttons since it thinks the layout is ambiguous. That is probably breaking the width constraint you set on the first button so the console output would contain a big log message that starts with
You can look at that and see if there’s any constraint in there that you don’t expect that could be causing the issue. Or you can post it here.
Neither
UITextView
norUICollectionView
have intrinsic heights – so the stack view doesn’t know what to do with their sizes.Most of what you have looks correct, but you need a couple changes.
First, you want your image view to be 33% or less of the view height? If so, don’t constrain the height of the image view to the height of
view
… constrain it to theOuterStackView
.Second, constrain the Height of the collection view equal to the Height of the text view.
Now, you’ll have:
Height: 40
Height: 40
(because the buttons are allHeight: 40
Here’s how it looks in Storyboard:
Notes:
StackView1 (the "Outer" stack view) is set to:
StackView2 (the labels stack view) is set to:
You’ll want to set the labels’ Hugging and Compression Resistance priorities to your liking.
StackView3 (the buttons stack view) is set to:
That should do it.