3

How to evenly space two subviews around the centre of UIStackView in the vertical axis?

Currently both labels are next to the top and the bottom of the StackView. The stack view is the greyed area on the simulator screen shot.

How to make them evenly spaced?

   |
   |
[UILabel]
   |
   |
[UILabel]
   |
   |

I've tried different configurations, but I couldn't get the desired result.

Here is my current code:

let object = UIStackView()
object.translatesAutoresizingMaskIntoConstraints = false
object.alignment = UIStackViewAlignment.Center
object.axis = .Vertical
object.distribution = UIStackViewDistribution.EqualSpacing
Tomasz Nazarenko
  • 1,064
  • 13
  • 31

2 Answers2

5

Considering you have similar properties set to UIStackView (as mentioned in the question)

   alignment -> Center 
        axis -> Vertical
distribution -> Equal Spacing

The solution can be achieved by introducing two empty views with height constraint set to 0 to both ends of UIStackView.

Explanation

On Adding two empty views of height 0, we are telling UIStackView that we have 4 views instead of 2. enter image description here

Now UIStackView will add equal spacing between all the views and hence the output.

enter image description here

You can cross verify it by looking at the height of the UIStackView and the position of the labels.

Hope this helps !!!

Ujwal Agrawal
  • 454
  • 7
  • 8
-1

In stackView attribute inspecter change spacing value from 0 to your preferred space value..

suma
  • 9
  • 1