Understanding SwiftUI Stacks: HStack, VStack, and ZStack

If you are designing your iOS app with SwiftUI, it’s essential to understand the basic concepts of Stacks, particularly HStack, VStack, and ZStack, and how to use them. In this tutorial, we will explore these three types of stacks.

HStack

HStack – H in HStack stands for Horizontal. This stack view arranges all the elements/views inside it horizontally. Below image has a HStack and inside the HStack we have 2 Text labels.

HStack {
  Text ("Hello" )
  .font(.title)
  .background (.yellow)
               
  Text ("World!")
  . font(.title)
 .background (.green)
}
 . padding()
 .background (.red)

VStack

VStack – V in VStack stands for Vertical. This stack will arrange all the elements/views inside it vertically. Below image is having a VStack and you can clearly see that it arranges views vertically rather than horizontally(which was the case when we used HStack)

Views added to VStack
VStack {
  Text ("Hello" )
  .font(.title)
  .background (.yellow)
               
  Text ("World!")
  .font(.title)
 .background (.green)
}
 . padding()
 .background (.red)

ZStack

ZStack – This stack view is different from both HStack and Vstack. When we add views to this ZStack, it aligns view on top of each other. Though we can change the appearance order of added views by giving them z-index value. Higher z-axis value than the one before it, means later sub-view appear “on top” of earlier ones.

ZStack containing rectangles of different colors

Summary

In this post, we learn about different types of stacks used in SwiftUI, i.e. HStack is used to place view horizontally, VStack is used to place views vertically and ZStack is used when we want views on top of each other inside a container view. Since stacks are the basic building block while we design iOS app using SwiftUI so we need to have basic understanding of these 3 stack views.