6

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok I just wondered if there is any environment property to check if is presented as sheet or navigation. Thank you for your answer and I will use extra showBanner property!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.