P. Ent
P. Ent

Reputation: 1823

How to Handle Safe Area Space in SwiftUI While Ignoring It

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?

Upvotes: 5

Views: 3189

Answers (3)

Farooq Haroon
Farooq Haroon

Reputation: 79

You can just Add ignoresSafeArea() to Color.yellow.Color.yellow.ignoresSafeArea() inside the .background() Modifier

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

Upvotes: 0

pawello2222
pawello2222

Reputation: 54611

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()
                }
            }
        }
    }
}

Upvotes: 4

vacawama
vacawama

Reputation: 154691

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))
        }
    }
}

Upvotes: 1

Related Questions