Change spacing between VStack elements in SwiftUI
In this tutorial, I will show you how to change or customize the spacing between VStack elements in SwiftUI.
In one of my previous tutorials, I discussed Custom space between Hstack elements in SwiftUI.
We can do this using the following ways: (You can choose what suits you best)
- Using spacing: inside VStack()
- With the help of Spacer().frame
- Using .padding(.bottom, value)
- Create our own Struct for Custom Spacer.
I will show each of those with example one by one.
I am taking an example by creating two Text() items in a VStack and then I will show you how easily we can change the space between those items.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
Text("I love CodeSpeedy")
Text("I also like SwiftSpeedy")
}
}
}
Output:

Change space between VStack elements by using spacing: value
We can simply use this:
VStack(spacing: spacing_value)
Check it:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 40){
Text("I love CodeSpeedy")
Text("I also like SwiftSpeedy")
}
}
}

Change spacing between VStack elements individually
Now if you want to change the spacing between specific two Vstack elements or items you can do this:
Spacer().frame(height: value)
Take a look at my code:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(){
Text("I love CodeSpeedy")
Spacer().frame(height: 20)
Text("I also like SwiftSpeedy")
Text("How's UISpeedy?")
}
}
}Output:

Change space using .padding(.bottom, value)
We can also do the same by using .padding(.bottom, value)
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(){
Text("I love CodeSpeedy")
.padding(.bottom, 20)
Text("I also like SwiftSpeedy")
Text("How's UISpeedy?")
}
}
}Output:

Our own Custom Spacer to add space between VStack elements
Just add this custom struct:
struct CustomSpacer: View {
var height: CGFloat
var body: some View {
Spacer()
.frame(height: height)
}
}The full code example:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(){
Text("I love CodeSpeedy")
CustomSpacer(height: 20)
Text("I also like SwiftSpeedy")
Text("How's UISpeedy?")
}
}
}
struct CustomSpacer: View {
var height: CGFloat
var body: some View {
Spacer()
.frame(height: height)
}
}This will show the same output as the previous one.
Leave a Reply