【问题标题】:How do I create a navigation stack with a dynamic number of elements?如何创建具有动态元素数量的导航堆栈?
【发布时间】:2021-04-28 20:39:08
【问题描述】:

我正在尝试在 swiftui 中创建一个标准的导航堆栈,更重要的是我可以拥有任意数量的页面。这是我的第一次尝试,但由于某种原因,在我尝试导航通过第一个列表元素后,我的选择变量不断重置为 null。

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() }

如果人们想查看目标代码的样子:

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))
}

这是下一个按钮的逻辑:

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)
    }
}

【问题讨论】:

  • 无法重现 - 你能做一个最小的例子吗?

标签: ios swift swiftui swiftui-navigationlink swiftui-navigationview


【解决方案1】:

所以我发现您需要在导航链接中添加一个 id 标签。我给了它一个默认的uuid。特别是如果它是在迭代中创建的。比如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多