I'm somewhat new to SwiftUI and I'm struggling to successfully pop to the root controller when clicking on a NavigationLink
in a row of a list. I'm following the approach demonstrated in this other post. I'm able to get this implementation working elsewhere in my project, but its a little tricky when a List is involved.
The setup is: ListView contains List and RowView. Clicking on the NavigationLink in RowView segues to View 2. Whats happening is that when I click on the NavigationLink it segues X times if there are X rows in the list. I'm assuming that by clicking on the NavigationLink, I am toggling it the binding bool to true, and as a result all NavigationLinks are being activated.
struct RowView : View {
@Binding var rootIsActive : Bool
var body: some View {
VStack() {
let view2 = View2(shouldPopToRootView: $rootIsActive)
HStack() {
NavigationLink(destination: view2, isActive: $rootIsActive, label: {Text("Go to view 2")}).isDetailLink(false)
.background(Color.purple)
// Additional UI stuff
}
.frame(height:50)
}
}
}
struct ListView: View {
@State var isActive : Bool = false
var someItems: [SomeObj] = []
var body: some View {
NavigationView {
VStack() {
// Other UI stuff
List {
ForEach(self.someItems) { item in
Section(header: RowView(rootIsActive: $isActive).onTapGesture {
// debug code
})
}
}
}
}
}
}
struct View2: View {
@Binding var shouldPopToRootView : Bool
var body: some View {
ZStack() {
//UI Stuff
}
.navigationBarItems(trailing: Button(action: {
// Pop to root
self.shouldPopToRootView = false
}, label: {
Text("Save")
}))
}
}