-->

W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

2/19/2020

What is different between VStack, HStack and ZStack in SwiftUI?

We don't know what is different between VStack, HStack and ZStack in SwiftUI? Let's look through these definitions in Apple Developer official website:


VStack

A view that arranges its children in a vertical line.

HStack

A view that arranges its children in a horizontal line.

ZStack

A view that overlays its children, aligning them in both axes.


These are three example about them


VStack :
If you have two elements in VStack, the two elements will in a vertical line,  as follows:

  1. VStack {
  2.     RoundedRectangle(cornerRadius: 10)
  3.         .fill(Color.yellow)
  4.         .frame(width: 80, height: 80)

  5.     RoundedRectangle(cornerRadius: 10)
  6.         .fill(Color.red)
  7.         .frame(width: 80, height: 80)
  8. }
Output :

Screenshot 2019-09-19 at 10.44.24 AM.png

HStack : 
If you have two elements in HStack, the two elements will in a horizontal line, as follows:

  1. HStack {
  2.     RoundedRectangle(cornerRadius: 10)
  3.         .fill(Color.yellow)
  4.         .frame(width: 80, height: 80)

  5.     RoundedRectangle(cornerRadius: 10)
  6.         .fill(Color.red)
  7.         .frame(width: 80, height: 80)
  8. }
Output :

Screenshot 2019-09-19 at 10.42.30 AM.png

ZStack : 
Arrange the elements in the Z index, if you have two element inside the ZStack then first element is below the second element, as follows:

  1. ZStack {
  2.     RoundedRectangle(cornerRadius: 10)
  3.         .fill(Color.yellow)
  4.         .frame(width: 200, height: 200)

  5.     RoundedRectangle(cornerRadius: 10)
  6.         .fill(Color.red)
  7.         .frame(width: 80, height: 80)
  8. }
Output :

Screenshot 2019-09-19 at 10.46.34 AM.png

I hope you will understand the different between VStack, HStack and ZStack in SwiftUI.

No comments:

Post a comment

Note: only a member of this blog may post a comment.