Centring a stack view

I have a stack view containing some text fields in a storyboard. I embeded the stack view in a scroll view to get it to move out of the way of the keyboard when required. All of that works fine.


I pinned the sides and bottom of the scroll view to the sides and bottom of the main view. But there are some labels at the top of the main view, so the top of the scroll view is pinned to the bottom of the lowermost label. So the distance between scroll view top and the main view top is significantly greater than the distance between scroll view bottom and the main view bottom.


When I constrain my stack view to be vertically centred within the scroll view, it looks off-centre. What I'd like to do is have the stack view vertically centered with respect to the main view, rather than the scroll view. How would I use constraints to do this?

I would try just adding that constraint. Stack view center Y = main view center Y. But give it a lower priority than whatever constraints you have positioning the stack view within the scroll view. That way when the scroll view forces scrolling, the higher priority constraints should take effect and the stack view will move.

Thanks for your answer, although I'm afraid I don't see how to do what you suggest. When I click on the Align button on the storyboard, and then check the Horizontally in Container and Vertically in Container boxes, the stack view gets centred relative to the scroll view. But I don't know how to change this to the main view instead. I'm sure I need to work through some more tutorials about storyboard constraints.


For present purposes, I've decided to use a static table view for my data entry, with the text fields planted in the table rows. That way I get scrolling for free, and setting the constraints is much easier. I also get the pleasure of deleting many hours of frustrating work from my storyboard.

You would use the document outline. There you can control-drag from any view to any other view. I usually make my constraints there; that way there's no chance Xcode will pick a different view than I expect, like it could if I were dragging between views on the canvas.


Yes for simple constraints (space to superview, nearest neighbour etc.) I will use the "tie fighter" or other menus, but the document outline is my go-to.

Centring a stack view
 
 
Q