Search code examples
swiftxcodeswiftui

Why is Spacer() expanding automatically expanding my VStack beyo


This is an image of my xcode along with the code and the canvas of whats happening.

I have used Color.green.ignoreSafeArea() to color the background of my ZStack. But when I set the background in line 34 to background(Color.white) it colors the are beyond safeArea to white as well I don't know why, shouldn't it just color the background of the VStack?

This is an Image of UI when I use the below code

When I use background(Color.white.cornerRadius(10)) instead in line 34 it starts behaving normally and only covers the safe areas? Has anybody got any explanation for this or is it just a bug ?

Here is the code used in the images:

struct MySignUpView: View {
var body: some View {
    VStack(spacing: 20){
        Image(systemName: "chevron.up")
            .padding(.top)
        Text("Sign up")
            .font(.headline)
            .fontWeight(.semibold)
        Image(systemName: "flame.fill")
            .resizable()
            .scaledToFit()
            .frame(width: 100, height: 100)
        Text("This is the best app in the world, if you subscribe to this application you will become a billionaire by age 30 .")
            .multilineTextAlignment(.center)
        
        Text("CREATE AN ACCOUNT")
            .font(.headline)
            .padding()
            .padding(.horizontal)
            .foregroundStyle(Color.white)
            .background(Color.black.cornerRadius(10))
        Spacer()
    }
    .frame(maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/)
    .background(Color.white.cornerRadius(20))
}

}


Solution

  • background(Color.white) ignores safe areas because the background modifier also takes a ignoresSafeAreaEdges argument, and this has the default value of .all.

    Note that the aforementioned background method takes a ShapeStyle, which Color.white conforms to. However, when you do .background(Color.white.cornerRadius(10)), Color.white.cornerRadius(10) is not a ShapeStyle. This calls another, deprecated overload of background that takes any View - background(_:alignment:). This modifier does not ignore safe areas by default.

    The non-deprecated version of that is background(alignment:content:).

    See also my answer here, which is a very similar situation.