In the previous tutorial about SwiftUI, we discussed how views can be organized using stacks. Now, let’s dive into the topic of spacing.
When using a VStack, you might notice that there is no space between the Text views by default. This is the default behavior of a VStack. However, you can adjust the spacing between the views by providing a spacing parameter:
VStack(spacing: 100) {
Text("Hello World")
Text("Hello again!")
}
In this example, we set the spacing to 100 points, resulting in a 100-point gap between the views within the VStack.
Alternatively, you can use a Spacer view to distribute the available space:
VStack {
Text("Hello World")
Spacer()
Text("Hello again!")
}
The Spacer view fills up all the available space it can find:
You can also restrict the spacing of the Spacer by using the frame() modifier:
VStack {
Text("Hello World")
Spacer()
.frame(height: 20)
Text("Hello again!")
}
By adding the .frame(height: 20) modifier, we limit the height of the Spacer to 20 points, resulting in a smaller gap between the views.
By understanding how spacing works in SwiftUI, you can create visually appealing and well-organized layouts for your apps.