swiftswiftui

VStack and Spacer placement in SwiftUI


Here is my sample code for my current View. I want my Vstack(with the brown bg) to be starting from top (having few top padding). I put a Spacer() for that but seems not quite working. Any help?

var body: some View {
        ZStack {
            // Background Image
            Image("companyLaunch")
                .resizable()
                .scaledToFill()
                .ignoresSafeArea()
            
            VStack {
                Image(systemName: "command")
                    .resizable()
                    .scaledToFit()
                    .frame(width: horizontalSizeClass == .regular ? 170 : 200, height: horizontalSizeClass == .regular ? 40 : 60)
                    .padding(.top, 20)
                
                Image(systemName: "building")
                    .resizable()
                    .scaledToFit()
                    .frame(width: horizontalSizeClass == .regular ? 300 : 200, height: horizontalSizeClass == .regular ? 225 : 150)
                
                
                Text("One place\nfor all your work.")
                    .font(.titilliumWebRegular(size: 25))
                    .multilineTextAlignment(.center)
                
                Text("Best-in-class system to advance your business.\nGet in Touch anytime, anywhere, track all activities\nand customizable based on needs.")
                    .font(.titilliumWebRegular(size: 15))
                    .multilineTextAlignment(.center)
                
                HStack {
                    Rectangle()
                        .frame(height: 1)
                        .foregroundColor(.black)
                }
                .padding(.horizontal, 40)
                
                mainContent
                
                
            }
            .background(Color.brown)
            Spacer()
        }
    }

enter image description here


Solution

  • Default alignment for ZStack is .center, also you put Spacer() in ZStack so it just expand entirely. A solution is changing alignment of ZStack to .top:

    ZStack(alignment: .top) { // <- change alignment here
    

    Another solution is wrap your brown View in another VStack then add Spacer to it:

    VStack {
        ... brown view
            .background(Color.brown)
        Spacer()
    }
    

    enter image description here