I am trying to use preference keys to mimic navigationBarTitle behavior. In particular I want a child preference key to bubble up and override one set by parent.
In this example I have defined a custom preference key and I set its value twice... right after also setting navigationBarTitle.
Notice that the navigationBarTitle value "Home 2" is overriding the "Home 1" value set in parent. I can't figure out how to also override the parent value of my custom preference key. No mater how I change my reducer function the final value is always the value set in parent, value == 1.
In this example I have defined a custom preference key and I set its value twice... right after also setting navigationBarTitle.
Notice that the navigationBarTitle value "Home 2" is overriding the "Home 1" value set in parent. I can't figure out how to also override the parent value of my custom preference key. No mater how I change my reducer function the final value is always the value set in parent, value == 1.
Code Block swift struct MyPreferenceKey: PreferenceKey { static var defaultValue: Int = 0 static func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } } struct MyPreferenceKeyView: View { @State var preference: Int = 0 var body: some View { VStack { Text("\(preference)") .navigationBarTitle("Home 2") .preference(key: MyPreferenceKey.self, value: 2) } .navigationBarTitle("Home 1") .preference(key: MyPreferenceKey.self, value: 1) .onPreferenceChange(MyPreferenceKey.self) { value in self.preference = value } } }