SwiftUI: How to use stacks using HStack and VStack?

Priyanka Saroha
2 min readSep 9, 2023

--

A stack is a collection of views which are grouped together. There are three kind of stack views are available i.e HStack, VStack and ZStack.

  • HStack: A horizontal stack view which shows views horizontally from left to right.
  • VStack: A vertical stack view which shows views vertically from top to bottom.
  • ZStack: A depth based stack view which shows views from back to front.

Below is the visual example:

Here are the some of options to align contents of VStack and HStack:

HStack:

  • .top: Align subviews to the top of the stack.
  • .bottom: Align subviews to the bottom of the stack.
  • .center: Align subviews in the middle (default).

VStack:

  • .leading: Align subviews to the left.
  • .center: Align them in the middle (default).
  • .trailing: Align views to the right.

Below is the code to show example of VStack:

Here is the code to show example of HStack:

Any view in SwiftUI is not allowed to have more than 10 child views. Below is the example of error when more than 10 child views are added to HStack:

Note: More than 10 child views are not allowed in SwiftUI and to have more than 10 child views use Group or Stack.

--

--

Priyanka Saroha

iOS developer with almost 9 years of rich experience which includes a good knowledge of ObjectiveC, Swift, SwiftUI and AR.