Search code examples
swiftuienvironment

SwiftUI: What is behaviour of Environment with NavigationLinks?


I have my custom Environment key in EnvironmentValues.

If I set value for such environment key using viewModifier .environment() Then If I navigatego to another view using NavigationLink this value will be erased ?

I think that only modals like .sheet or NavigationView prevents passing environment values to descendants views. Is it also true for NavigationLinks?

struct MyView: View { 

  var body: some View { 
       View1().environment(\.key, value)
  }
}

struct View1: View { 
 var body: some View { 
   NavigationLink(isActive: $isActive) { 
      View2()
 } 
}

So in above case @Environment(\.key) inside View2 doesn't return passed value?


Solution

  • The value is not passed because View2 is not a child of View1. You will have to add the environment on the NavigationView parent.