0

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"))
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209

1 Answers1

1

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()
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • at the line "func moduleView(name: String) -> some View {" I get the error "Function declares an opaque return type, but the return statements in its body do not have matching underlying types" – mLuckhurst Jun 03 '20 at 22:31
  • Did you replace `View1()`, `View2()` with your Views? – pawello2222 Jun 03 '20 at 22:33
  • Yes I did: code: func moduleView(name: String) -> some View { switch name { case "Organic Chemistry 1": return Organic1Quiz() case "Organic Chemistry 2": return Organic2Quiz() case "Physical Chemistry 1": return Physical1Quiz() case "Inorganic Chemistry 1": return Inorganic1Quiz() case "General Chemistry": return GeneralChemistryQuiz() case "Mathematics for Chemists": return MathematicsForChemistsQuiz() default: return HomeView() } } – mLuckhurst Jun 03 '20 at 22:36
  • I updated my answer. Now you can return whatever you want: `Button`, `Text`... (as long as it conforms to `View`). – pawello2222 Jun 03 '20 at 22:38