Search code examples
iosxcodeuiscrollviewautolayoutuistackview

How can I center items horizontally inside uistackview


I have a UIScrollView and an UIStackView. I want to add elements from top to bottom and let the scrollview scroll only vertically. I have trouble with this and don't really get what the problem is.

So I added the constrains that the UIScrollView should stick to the super view on all sides, added the stackview, you can see its constrain on the pic, also added a label with fixed width. I want this label to be center in the scrollview without the scrollview starting to scroll horizontally.

I think Im missing some constrains? The scroll view also says it has "ambiguous scrollable content width".

enter image description here


Solution

  • First to fix ambiguous you should create a contentView for the scrollView as Apple recommends and give it width of outmost view then put the stackView inside it and Change alignment of the stackview to .center + alignment of the label itself

           Scrollview  // pinned to top , leading , trailing ,bottom
              contentView // pinned to top , leading , trailing ,bottom , and have width = outmost view (very important)
                 stackView