I'm having a problem with old views that have been popped from the navigation stack still seems to be "updated" in the background even though they are not visible or on the navigation stack. I do the following:
Sample code:
In the sample, clicking a row in the list simply uses SubView to show the number and also log it to the console. If I return to the main view and click the Add button to force an update of the binding variable, the log will show that the SubView is being updated again.
It seems that I can fix it using:
But that just seems silly and I'm not sure it will work in all situations.
Am I doing something wrong? Is this expected behaviour? Is there any way I can stop the SubView from updating after it has been dismissed?
The main view is pushing a sub view on the navigation stack. The sub view becomes visible.
The user uses the back arrow to go back, popping the sub view from the navigation stack. The main view is now visible.
The main view updates and this seems to cause the sub view to also update, even though it shouldn't be active.
Sample code:
Code Block language import SwiftUI struct ContentView: View { var body: some View { TestView(items: [1, 2, 3, 4, 5]) } } struct TestView: View { @State var items: [Int] var body: some View { NavigationView { VStack { Text("Hello") List { ForEach(items, id: \.self) { item in NavigationLink(destination: SubView(items: self.$items, number: item)) { Text("\(item)") } } } Button(action: { self.items.append(self.items.count + 1) }) { Text("Add") } } } } } struct SubView: View { @Binding var items: [Int] var number: Int var body: some View { Group { Print("\(number)") Text("\(number)") } } } extension View { func Print(_ items: Any..., separator: String = " ", terminator: String = "\n") -> some View { let output = items.map { "\($0)" }.joined(separator: separator) Swift.print("→ " + output, terminator: terminator) return EmptyView() } }
In the sample, clicking a row in the list simply uses SubView to show the number and also log it to the console. If I return to the main view and click the Add button to force an update of the binding variable, the log will show that the SubView is being updated again.
It seems that I can fix it using:
Code Block language struct SubView: View { @Binding var items: [Int] var number: Int @State var active = true var body: some View { Group { if active { Print("\(number)") Text("\(number)") } } .onDisappear { self.active = false } } }
But that just seems silly and I'm not sure it will work in all situations.
Am I doing something wrong? Is this expected behaviour? Is there any way I can stop the SubView from updating after it has been dismissed?