0

I'm trying to create a standard navigation stack in swiftui, the kicker is that I can have any number of pages. Here is my first attempt but for some reason my selection variable keeps getting reset to null after I attempt to navigate passed the first list element.

PrimerView()
ForEach(vm.sections!.indices) { index in
    NavigationLink(destination: formSection(vm.sections![index]),
                   tag: index,
                   selection: $vm.sectionIndex) { EmptyView() }
}
NavigationLink(destination: formConfirmation, tag: vm.sectionsCount, selection: $vm.sectionIndex) { EmptyView() }

and in case people want to see what the destination code looks like:

func formSection(_ section: FormSection) -> some View {
    ScrollView {
        VStack {
            Text("REQUIRED_HINT".localized)
                .font(.subheadline)
                .padding(.vertical)
            ForEach(section.questions) { question in
                QuestionAndAnswerView(question: question)
            }
            nextButton
                .disabled(section.canProgress)
        }
    }
    .navigationTitle(sectionDescription)
    .navigationBarTitleDisplayMode(.inline)
    .padding()
    .background(Color(.systemGroupedBackground))
}

var formConfirmation: some View {
    VStack {
        FormConfirmationView(FormConfirmation(taskName: vm.title, points: vm.primer.points ?? 0))
        nextButton
    }
    .padding()
    .background(Color(.systemGroupedBackground))
}

and here is the next button logic:

var nextButton: some View {
    Button(action: {
        if isLastIndex {
            dismiss()
        } else if vm.sectionIndex == nil {
            vm.sectionIndex = 0
        } else if let index = vm.sectionIndex {
            vm.sectionIndex = index + 1
        }
    }) {
        Text((vm.sectionIndex ?? 0) >= vm.sectionsCount ? "NAV_DONE".localized : "NAV_NEXT".localized)
            .font(.title3)
            .frame(maxWidth: .infinity)
            .frame(height: 50)
            .foregroundColor(.white)
            .background(Color.blue)
            .cornerRadius(10)
            .padding(.bottom, 40)
    }
}

1 Answers1

0

So I figured out that you need to add an id tag to the nav links. I gave it a default uuid. especially if its being created in an iteration. so for instance:

NavigationLink(destination: destination, tag: tag, selection: selection) { EmptyView() }
    .id(UUID())