How to Handle Safe Area Space in SwiftUI While Ignoring It

1.9k views Asked by At

I want to completely color the background of my app while at the same time positioning content at the top so that its far enough from the status bar and top notch on those devices that have it.

If I do something like this:

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            VStack {
                Text("Top of my view")
                Spacer()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.yellow)
        }
    }
}

This displays the text at the top of the content, below the safe area. But only the content area is yellow. The safe areas are white.

So I add .edgesIgnoringSafeAreas(.all) below the .background modifier.

Now my text is below the notch (or smack up at the top of the screen below the Status bar text) and not visible.

I don't want to randomly guess at a top padding because that might be fine on phones with notches but look wrong on phones or iPads without notices.

If I place my VStack inside of a GeometryReader, the reader.safeAreaInsets.top is zero (0) when the top safe area is ignored.

I hope this a clear enough question. Has anyone run into this and have a solution?

2

There are 2 answers

1
pawello2222 On BEST ANSWER

You need to apply the edgesIgnoringSafeArea modifier to Color.yellow only.

A possible solution is to use a ZStack:

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                Color.yellow
                    .edgesIgnoringSafeArea(.all)
                VStack {
                    Text("Top of my view")
                    Spacer()
                }
            }
        }
    }
}
1
vacawama On

One way to fix it is to apply .edgesIgnoringSafeArea(.all) just to the Color.yellow inside of .background():

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            VStack {
                Text("Top of my view")
                Spacer()
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.yellow.edgesIgnoringSafeArea(.all))
        }
    }
}