I have a custom environment variable, like:
public enum Something: CaseIterable {
case thing
case other
}
public struct SomethingKey: EnvironmentKey {
public static var defaultValue: Binding<Something> = .constant(.thing)
}
public extension EnvironmentValues {
var something: Binding<Something> {
get { self[SomethingKey.self] }
set { self[SomethingKey.self] = newValue }
}
}
public extension View {
func something(_ value: Binding<Something>) -> some View {
environment(\.something, value)
}
}
I wish to pass it on at the top level view. But this didn’t work, the environment variable kept its default value. I found out it does not seem to propagate through a NavigationLink
, as I show below:
@State var something: Something = .thing // Is being set by a Picker(); code not shown.
...
NavigationLink(destination: TabView {
MyView()
.something($something) // Works here.
}
.something($something) // Works here also.
) {
Text("Tab")
}
.something($something) // Does NOT work here.
Why is that and what can I do about it?