In this tutorial, I am going to discuss the Stacks in SwiftUI with the help of examples.
With the help of Stacks, you can arrange and organize multiple views into a single view with certain properties. In a nutshell, Stacks are used to grouping multiple views together. A stack can contain multiple subviews or child views inside it.
SwiftUI provides 3 types of stacks that you can use to arrange child views. These are VStack, HStack and ZStack. Below I am discussing each type of stack with examples…
VStack is used for arranging its child views vertically or you can say from top-to-bottom. Below is given an example of using VStack in SwiftUI:
struct ContentView: View {
var body: some View {
VStack {
Text("Some Text")
Text("Another Text")
}
}
}
Below is given the screenshot for the above code on an emulator or any iOS device:
In the above screenshot, you can see that the text views are arranged top-to-bottom or vertically. This is because these text views are the child views of VStack.
HStack in SwiftUI arranges its child views horizontally or you can say side by side. Below is an example of using HStack:
struct ContentView: View {
var body: some View {
HStack {
Text("Some Text")
Text("Another Text")
}
}
}
Running the view file on an iOS device will show the texts side-by-side as you can see in the screenshot below:
ZStack allows you to overlap its child views on top of each other or you can say arrange child views back-to-front. If we put our text views into a ZStack, then it will be a lot harder to read. This is because these text views overlap each other.
Below is given an example of using ZStack:
struct ContentView: View {
var body: some View {
ZStack {
Text("Some Text")
Text("Another Text")
}
}
}
Running the above program gives you the result given in the screenshot below:
Don’t be surprised if you can’t read the text in the above screenshot. This is because the text views overlap each other. This is what exactly ZStack does.