swiftswiftuivstackzstack

SwiftUI Zstack – Make element ignore safe area and another one don't


I have a Zstack like this:

ZStack {
  Image("beach")
    .resizable()
    .edgesIgnoringSafeArea(.all)
    .scaledToFill()

  VStack {
    // with a lot of stuff
  }
}

I want the image to ignore the safe area, but the Vstack must respect the safe area.

The image is a background image that should cover all the area.

This code I have is making the VStack full screen too and I don't want that.

Why everything is not respecting the safe area is a mystery, because the respective modifier is applied to the image only.


Solution

  • Put your image in the .background:

    struct ContentView: View {
        var body: some View {
            
            VStack {
                // lots of stuff
                Color.red
                Color.blue
            }
            .background(
                Image("beach")
                    .resizable()
                    .edgesIgnoringSafeArea(.all)
                    .scaledToFill()
            )
        }
    }