Stacks - HStack, VStack And ZStack In SwiftUI

Introduction

 
When creating a SwiftUI view, you describe its content, layout, and behavior in the view's body property, however the body property only returns a single view. You can combine and embed multiple views in Stacks, which group views together horizontally, vertically, or back to front. 
 
SwiftUI provides three distinct stacks,
  • HStack -  which arranges its children(i.e. subviews) in a horizontal line, next to each other.
  • VStack -  which arranges its children in a vertical line, i.e above and below each other.
  • ZStack  - which overlays its children, i.e. places them on top of each other, back to front, along the z depth axis.
Example
 
Horizontal Stack,
  1. import SwiftUI  
  2.   
  3. struct ContentView: View {  
  4.     var body: some View {  
  5.         VStack {  
  6.             Text("Stunning Landscape Picture!!")  
  7.                 .font(.title)  
  8.             Image("landscape")  
  9.                 .clipped()  
  10.             HStack {  
  11.                 Text("Senior iOS developer")  
  12.                     .font(.subheadline)  
  13.             }  
  14.         }  
  15.     }  
  16. }  
  17.   
  18. struct ContentView_Previews: PreviewProvider {  
  19.     static var previews: some View {  
  20.         ContentView()  
  21.     }  
  22. }  
Stacks - HStack, VStack And ZStack In SwiftUI
 
Example
 
Vertical Stack,
  1. import SwiftUI  
  2.   
  3. struct ContentView: View {  
  4.     var body: some View {  
  5.         VStack {  
  6.             Text("Stunning Landscape Picture!!")  
  7.                 .font(.title)  
  8.             Image("landscape")  
  9.                 .clipped()  
  10.               
  11.         }  
  12.     }  
  13. }  
  14.   
  15. struct ContentView_Previews: PreviewProvider {  
  16.     static var previews: some View {  
  17.         ContentView()  
  18.     }  
  19. }  
Stacks - HStack, VStack And ZStack In SwiftUI
 
ZStack for arranging things by depth - it makes views that overlap. In the case of our two text views, this will make things rather hard to read,
 
Example
  1. ZStack {  
  2.     Text("Hello Guys")  
  3.     Text("This is inside a stack")  
  4. }   
ZStack doesn't have the concept of spacing because the views overlap, but it does have alignment. So if you have one large thing and one small thing inside your ZStack, you can make both views align to like this ZStack (alignment: .top)  
 
ZStack draws its contents from top to bottom, back to front. This means if you have an image then some text ZStack will draw them in that order, placing the text on the top of the image.


Similar Articles