简体   繁体   English

每个列表元素可以导航到 SwiftUI 中的新视图吗?

[英]Can each list element navigate to a new view in SwiftUI?

I am new to SwiftUI and I am trying to create a list featuring each module taken at a university degree.我是 SwiftUI 的新手,我正在尝试创建一个包含大学学位课程的每个模块的列表。 I would like (when clicked on) each module to navigate to a separate, new, view.我希望(单击时)每个模块导航到单独的新视图。 This is what I hope to achieve:这是我希望达到的目标:

HomePage -> ListPage -> each respective module page. HomePage -> ListPage -> 每个相应的模块页面。

NavigationLink only seemed to have one possible destination for all list elements. NavigationLink对于所有列表元素似乎只有一个可能的目的地。 Is there any way of doing this?有没有办法做到这一点? Thank you in advance.先感谢您。 This is my current code:这是我当前的代码:

struct ListView: View {
    var modules: [Module] = []
    var body: some View {
        NavigationView {
        List(modules) { module in
            NavigationLink(destination: QuizView()) {
            VStack(alignment: .leading) {
                Text(module.name)
                Text("\(module.questions) questions")
                    .foregroundColor(.secondary)
                    .font(.subheadline)

            }
            }
        }
        .navigationBarTitle(Text("Modules"))
        }
    }
}

You can try returning a specific View based on some value (eg. module.name ):您可以尝试根据某个值(例如module.name )返回特定View

var modules: [Module] = []
var body: some View {
    NavigationView {
        List(modules) { module in
            NavigationLink(destination: moduleView(name: module.name)) {
                VStack(alignment: .leading) {
                    Text("\(module.id)")
                }
            }
        }
        .navigationBarTitle(Text("Modules"))
    }
}
@ViewBuilder
func moduleView(name: String) -> some View {
    switch name {
    case "module 1":
        View1()
    case "module 2":
        View2()
    default:
        View3()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM