EN VI

SwiftUI overlay respect safe Area?

2024-03-12 01:30:04
How to SwiftUI overlay respect safe Area

I have an overlay in my SwiftUI view as follows (for simplicity purpose, I have a view with plain blue color in the code below):

   .overlay(alignment: .bottom, content: {
        showMenu ? Color.blue.frame(height: 150) : nil
    })

My problem is that it does not respect safe area in landscape mode and I see no way to customize it so that the overlay does not cross dynamic island on iPhone 14/15 pro. It is okay to target iOS 16 and above if that simplifies things.

Solution:

Do you mean, the overlay is not extending into the safe area?

A pre-requisite for this to be possible is that the view the overlay is being applied to must be in contact with the safe area insets. Then, just apply .ignoresSafeArea() before applying the .frame:

EDIT If you only want it to respect the side insets, but still ignore the bottom insets, then you need to specify the edges for .ignoreSafeArea()

@State private var showMenu = true

var body: some View {
    Text("Hello")
        .ignoresSafeArea()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .overlay(alignment: .bottom) {
            showMenu
                ? Color.blue
                    .ignoresSafeArea(edges: [.bottom])
                    .frame(height: 150)
                : nil
        }
}

Screenshot

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login