I am new to SwiftUI and I am trying to create a list featuring each module taken at a university degree. 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.
NavigationLink
only seemed to have one possible destination for all list elements. 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
):
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()
}
}