Home > Software design >  SwiftUI VStack - make the background fill the entire screen in landscape
SwiftUI VStack - make the background fill the entire screen in landscape

Time:01-22

The background doesn't fill the entire screen in landscape. How can I make it stretch all the way?

White margins on the horizontal sides of the black background

Here's my code:

import SwiftUI

struct ContentView: View {
    @Environment(\.verticalSizeClass) var verticalSizeClass
    
    var body: some View {
        VStack(spacing: 20) {
            VStack {
                Text("Instant Developer")
                    .font(.system(.largeTitle))
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                Text("Get help from expert in 15 minutes")
                    .foregroundColor(.white)
            }
            
            HStack(alignment: .bottom, spacing: 20) {
                Image("student")
                    .resizable()
                    .scaledToFit()
                Image("tutor")
                    .resizable()
                    .scaledToFit()
            }
            .padding(.horizontal, 50)
            
            Text("Need help with coding problem? Register!")
                .foregroundColor(.white)
            
            Spacer()
            
            if verticalSizeClass == .compact {
                HSignUpButtonGroup()
            } else {
                VSignUpButtonGroup()
            }
        }
        .padding(.top, 30)
        .background(Color.black)
    }
}

CodePudding user response:

The problem seems to be because of scaledToFit, which tries to preserve the image's aspect ratio and so doesn't make the background extend all the way.

To fix, just make the background stretch as much as it can with .frame(maxWidth: .infinity). Make sure to put this modifier before background so that the color respects the new layout.

.padding(.top, 30)
.frame(maxWidth: .infinity) /// here!
.background(Color.black)
  •  Tags:  
  • Related