SwiftUI presentationMode: Check if view is presented by sheet

Viewed 682

There are two ways to show LoginView in my code

  1. In A view, use navigationLink
NavigationLink(destination: LoginView()) {
  Text(“To login")
 }
  1. In B view, use .sheet
.sheet(isPresented: $viewModel.isShowingSheet) {
    LoginView()
}

and in LoginView, I want to show my Banner if LoginView is presented as sheet, so I used presentationMode.

struct LoginView: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        if presentationMode.wrappedValue.isPresented {
            Banner()
        }
    }
}

But Banner is shown in both cases (navigation link and sheet)

Is it any good way to check if view is presented by sheet? Or do I have to inject presentation style using my own property?

1 Answers

Why not just pass in the value when creating the LoginView?

struct LoginView: View {
    var showBanner = false
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        if showBanner {
            Banner()
        }
    }
}

And when you call it as a sheet presentation:

.sheet(isPresented: $viewModel.isShowingSheet) {
    LoginView(showBanner: true)
}

And if you pass it from anywhere else, initialise it with false.

NavigationLink(destination: LoginView(showBanner: false)) {
  Text(“To login")
 }

There's nothing wrong with being explicit and telling the view when to show something, rather than have the view go through extra hoops to decide what to show. And this explicitness makes it easier to test the View.

Related