My problem all the time is how to center one element inside the stack view
Please look at my screenshots below to explain:
Number 1) Is the main StackView
Number 2) Is the concerned StackView which I want to make its content ( UIView in No 3 ) centering inside it
Number 3) This UIView I want to center it inside No.2 and give it a smaller width matching the blue line in the pic
Note: The problem is when I give a fixed width to the UIView in No.3 it always affect the scroll view behind the main StackView and shrink it !!
Here below is the configuration of the main StackView in No.1
Here below is the configuration of the sub StackView in No.2
As I said when I give a fixed width to the UIView in No.3 it always shrink and damage the scrollView which is in the App background
So can you help how to deal with this issue please?
I'm assuming you don't actually want the green color - that's just to make the view visible.
What you probably want to do is embed the horizontal stack view (containing the two buttons) in the green view, instead of the other way around (as you have it now).
Try it like this:
MainStack settings:
BtnsStack settings (I'm guessing you want some space between the buttons - I used 8
):
Here's how it looks at run-time, with the green BtnsStackHolderView
background set to clear:
and, rotated to show the buttons remain centered horizontally:
Edit how to center the green view inside the stackView without embed it inside another View?
The reason your green view is not centered in the stack view is because you have your stack view's Alignment
set to Fill
, which stretches the arranged subviews to Fill the Width of the stack view.
For a stack view with a Vertical
axis, alignment options are:
Here is an example with Center
(the stack view itself is constrained Top / Leading / Trailing 40-pts from the edges):
Starting from the bottom...
The blue wEqToStack h60
view is constrained:
The yellow w200 h60
view is constrained:
The orange wNone h60
view is constrained:
And the green BtnsStackHolderView
has no width or height constraints... its size is determined by constraints to its content (the BtnsStack
with 20-pts on each side).
If we run this, we see (red dashed line is just to show the frame of the stack view):
Whoops! Where did the orange view go? Since we didn't give it a width constraint, and the stack view's Alignment
is set to Center
, it ends up with a width of Zero.
So, if most of the views in your stack view have their own width defined, using center reduces the number of "containing" views needed. But if most of the views need to stretch the width of the stack view, it's probably easier to embed content you want centered in "containing" views.