How to check if a SwiftUI View is presented modally


Greetings, traveler!

At times, we may want to establish varying behaviors for the view based on different presentation options. We can do this with minimal effort in SwiftUI.

We will use the isPresented EnvironmentValue for this purpose. We can create a property with the Environment property wrapper to read this value.

struct DemoView: View {
    
    @Environment(\.isPresented) var isPresented
    
    var body: some View {
        Rectangle()
        .ignoresSafeArea()
    }
}

Now, we can determine the background color depending on the value of this property. However, we should duplicate this value inside another state property for correct color management. We will change its value inside the onAppear closure.

struct DemoView: View {
    
    @Environment(\.isPresented) var isPresented
    @State var isPresentedModally: Bool = false
    
    var body: some View {
        Rectangle()
        .fill(isPresentedModally ? Color.red : Color.blue)
        .onAppear {
            isPresentedModally = _isPresented.wrappedValue
        }
        .ignoresSafeArea()
    }
}

Everything is ready for testing.


struct ContentView: View {
    
    @State var isShow: Bool = false
    
    var body: some View {
        NavigationStack {
            Button("Present") {
                isShow.toggle()
            }
            
            NavigationLink("Push") {
                DemoView() // Blue color
            }
        }
        .fullScreenCover(isPresented: $isShow) {
            DemoView() // Red color
        }
    }
}

Nice!