WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Why does View background extend into safe area?

Forums > SwiftUI

Here's a view that navigates to a 2nd view:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                SecondView()
            } label: {
                Text("Go to 2nd view")
            }
        }

    }
}

 struct SecondView: View {
     var body: some View {
         ZStack {
             Color.red
             VStack {
                 Text("This is a test")
                     .background(.green)
                 //Spacer() // <--If you add this, it pushes the Text to the top, but its background no longer respects the safe area--why is this?
             }
         }
     }
 }

On the 2nd screen, the green background of the Text view only extends to its border, which makes sense because the Text is a pull-in view:

https://www.flickr.com/photos/195302002@N08/51947488140/in/dateposted-public/

Now, if you add Spacer() after the Text(), the Text view pushes to the top of the VStack, which makes sense, but why does its green background suddenly push into the safe area?

In the Apple documentation here, it says:

By default, SwiftUI sizes and positions views to avoid system defined safe areas to ensure that system content or the edges of the device won’t obstruct your views. If your design calls for the background to extend to the screen edges, use the ignoresSafeArea(_:edges:) modifier to override the default.

However, in this case, I'm not using ignoresSafeArea, so why is it acting as if I did, rather than perform the default like Apple says, which is to avoid the safe areas? Here's a pic of what it actually looks like, versus what I thought it would look like:

https://www.flickr.com/photos/195302002@N08/51947193734/in/dateposted-public/

   

Nice! Now please mark your answer as "Solved" !

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.