Spacing between elements in SwiftUI?

Viewed 1194

I wonder why does this spacing appear between 2 elements in SwiftUI? And how to control/modify it? I tried adding some paddings to ExtractedView but it changed nothing. It seems like it's somehow caused by .frame(height: 56) but this is exactly the height of the button, so it shouldn't lead to any spacing.

Code:

import SwiftUI

struct FirstLaunchView: View {
    var body: some View {
        VStack {
            ZStack {
                Image("first-launch")
                    .resizable()
                    .scaledToFill()
                    .frame(height: 483)
                Text("AppName")
                    .font(.custom("Lobster", size: 24))
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                    .frame(height: 483, alignment: .top)
                    .offset(x: 0, y: 61)
            }

            ZStack {
                VStack {
                    ExtractedView(title: "Start", textColor: Color.secondaryColor, bgColor: Color.primaryColor)
                    ExtractedView(title: "Log in", textColor: Color.primaryColor, bgColor: Color.secondaryColor)
                }
            }
            
            Spacer()
            
        }
        .ignoresSafeArea()
        
    }
}

struct ExtractedView: View {
    var title: String
    var textColor: Color
    var bgColor: Color
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 27.5)
                .fill(bgColor)
                .frame(width: 279, height: 56)
            RoundedRectangle(cornerRadius: 27.5)
                .strokeBorder(Color.primaryColor, lineWidth: 2)
                .frame(width: 279, height: 56)
            Text(title)
                .font(.custom("NotoSans-Regular", size: 18))
                .fontWeight(.bold)
                .foregroundColor(textColor)
        }
        .frame(height: 56)
    }
}
2 Answers

VStack has default spacing, so in

VStack {
    ExtractedView(title: "Start", textColor: Color.secondaryColor, bgColor: Color.primaryColor)
    ExtractedView(title: "Log in", textColor: Color.primaryColor, bgColor: Color.secondaryColor)
}

you give SwiftUI rights to decide which default spacing should be applied between internal views.

If you want explicit spacing, you can specify it, like

VStack(spacing: 25) {    // << here !!
  // ... views here
}

SwiftUI's VStack has a default padding, so if you don't want any, what you would need to do is:

VStack(spacing: 0) {
    // your code goes here
}

This also allows you to have your own spacing, such as

VStack(spacing: 40) { // 40 is the custom spacing
    // your code goes here
}
Related