Stack View
We often face a situation where we have more than two UI elements on a single row of the screen; then, it becomes really hard to align them proportionately with spacing using layout constraints. We can use UIStackView to deal with that situations.
For example, our goal is to have something like the following:

There are three buttons, and we want to align them perfectly with each other without working with custom constraints.
Designing View with UIStackView:
Let's create a new App and name it "StackViewDemo." Create a new file called StackView.swift, and put the following code there:
In the above code, we have three buttons and a stack to hold these three buttons.
On lines 11 through 15, we declare the buttons and the stack.
On lines 30 through 37, we define the stack.
On line 32, we define the axis of the stack. There are two possible axes: horizontal and vertical. The horizontal stack grows horizontally from left to right. The vertical stack grows downward, from top to bottom.
Line 33 is commented out but important. If the stack is vertical, you might want to align the UI elements since we will have empty spaces on both sides.
Line 34 talks about empty space distribution. I used
filledProportionally. It means the row is filled with the UI elements while keeping proportional spaces between them. It dynamically adjusts the empty spaces. You do not have to write complex constraints for them.
On lines 38 through 57, we define three buttons, just as always. However, the most important thing here is we are not adding the buttons as the sub-view of
selfhere. We are adding the buttons as the arranged sub-views of the stack.On lines 60 through 66, we are defining the constraints for the screen. See how easy it is to set up the layout constraints for stacks. We define the stack view's top, leading, and trailing anchors here. The stack height is automatically dealt with by the UI elements we added to the stack.
Patching ViewController
Now, let's load the view we created in the ViewController.swift file.
Run the App
If we run the app now, we will see:

If we change the axis to vertical ( stack.axis = .vertical ), the screen will look like:

Last updated
Was this helpful?