Я предполагаю, что вам на самом деле не нужен цвет зеленый - это просто для того, чтобы сделать вид видимым.
Что вы, вероятно, захотите сделать, так это встроить представление горизонтального стека ( содержащий две кнопки) в зеленом виде, а не наоборот (как сейчас).
Попробуйте это так:
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:
- Fill
- Leading
- Center
- Trailing
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:
- height = 60
- width equal to the stack view's width
The yellow w200 h60
view is constrained:
The orange wNone h60
view is constrained:
- width = no width constraint set
- height = 60
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):
введите описание изображения здесь
Упс! Откуда взялся оранжевый вид go? Поскольку мы не давали ему ограничения по ширине, а для представления стека Alignment
установлено значение Center
, ширина в конечном итоге будет равна нулю.
Итак, если большинство представлений в вашем стеке view имеют собственную ширину, использование center уменьшает количество необходимых «содержащих» представлений. Но если большинству представлений необходимо увеличить ширину представления стека, вероятно, проще встроить контент, который вы хотите центрировать, в "содержащие" представления.