0

The answer here works tremendously but, as Im sure, is not ideal for everyone. Say ContentView2, in the link, is looping a list of NavigationLinks, when self.$isActive is true, it triggers all the NavigationLinks to open so not ideal. I've found out about using tag and selection.


// Inside a ForEach loop
// Omitted is the use of EnvironmentObject

NavigationLink(
    destination: DestinationView(id: loop.id),
    tag: loop.id,
    selection: self.$routerState.selection,
    label: {
        NavCell(loopData: loop)
    }
)
.isDetailLink(false)


// State:
class RouterState: ObservableObject {
    //@Published var rootActive: Bool = false
    @Published var tag: Int = 0
    @Published var selection: Int? = nil
}

How to pop the NavigationLink when inside of a loop? The answer in the link works but not inside a loop. Is there a way to amend the answer to use both tag and selection?

Using example from link above:

import SwiftUI

struct ContentView: View {
    @State var isActive : Bool = false

    var body: some View {
        NavigationView {
            List {
                /// Data from the loop will be passed to ContentView2
                ForEach(0..<10, id: \.self) { num in 
                
                    NavigationLink(
                        destination: ContentView2(rootIsActive: self.$isActive),
                        isActive: self.$isActive
                    ) {
                        Text("Going to destination \(num)")
                    }
                    .isDetailLink(false)
     
                }
            }
        
        }
    }
}

struct ContentView2: View {
    @Binding var rootIsActive : Bool

    var body: some View {
        NavigationLink(destination: ContentView3(shouldPopToRootView: self.$rootIsActive)) {
            Text("Hello, World #2!")
        }
        .isDetailLink(false)
        .navigationBarTitle("Two")
    }
}

struct ContentView3: View {
    @Binding var shouldPopToRootView : Bool

    var body: some View {
        VStack {
            Text("Hello, World #3!")
            Button (action: { self.shouldPopToRootView = false } ){
                Text("Pop to root")
            }
        }.navigationBarTitle("Three")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Sylar
  • 11,422
  • 25
  • 93
  • 166
  • Can you provide some example code that demonstrates the scenario to test with? – jnpdx Feb 11 '21 at 06:17
  • Hi. I've added the loop with code taken from the answer in link – Sylar Feb 11 '21 at 06:35
  • Hacked away at this for a while with no luck -- didn't expect that none of my normal tricks would work in the `ForEach` loop as you pointed out. Following in hopes that you find a solution to this. – jnpdx Feb 11 '21 at 18:14
  • Thanks! I’ll keep trying and hopefully blog about it – Sylar Feb 11 '21 at 19:11

0 Answers0