When programming in SwiftUI we use some view for the body of the code. What this means is that the body is looking for a singular view. When a new SwiftUI view is created by default this view is a text view.
Text(“Hello World!”)
But this could be a number, image or even a shape. It just has to be something that fills the body. The issue with this is that if we try to put more than one type of view in the body we get some problems. The way we organise multiple views, whatever they are, is by using Stacks.
We use stacks in SwiftUI by using the stack you want to use and enclosing the views inside:
VStack { Text(“Hello World”) Text(“Hello World”) Text(“Hello World”) }
There are three types of stacks that we use in programming in SwiftUI:
VStack: Stack up to 10 views on top of each other so they are displayed vertically
HStack: Stack up to 10 views next to each other so they are displayed horizontally
ZStack: Stack up to 10 views over the top of one another so that they are displayed stacked
These stacks can be used in any combination to arrange views in the way to get the result you want. For example if you want to create a grid of 3 x 3 you can use a number of HStacks and VStacks together.
VStack { HStack{ Text(“Hello World!”) Text(“Hello World!”) Text(“Hello World!”) } HStack{ Text(“Hello World!”) Text(“Hello World!”) Text(“Hello World!”) } HStack{ Text(“Hello World!”) Text(“Hello World!”) Text(“Hello World!”) } }
Using SwiftUI there is a whole world open for you to design what you want by using stacks. Play around and experiment and create different views. Its an awesome way to learn and get rewarded too create awesome layouts for your apps.