How to create SwiftUI List of NavigationLinks with dynamic view names

810 views Asked by At

I am trying to create a simple list of Views for the user to visit, I cannot figure out how to replace view name with an array variable. In the example below destination: is hard coded as AVExample(), which is one of my views, but how do I use the names in the array?

struct test: View {
    
   var views = ["AVExample", "ColorPickerExample", "DatePickerExample"]
   
    var body: some View {
        
        NavigationView {
            List (views, id: \.self){ view in
                
                NavigationLink(
                    destination: AVExample(),
                    label: {
                        Text("\(view)")
                    })
            }
        }
    }
}
2

There are 2 answers

0
Anjali Aggarwal On

You can create a struct for the views and then use that array of structure. For Example:

 struct ViewsList: Identifiable {
    static func == (lhs: ViewsList, rhs: ViewsList) -> Bool {
        return lhs.id == rhs.id
    }
    
    var id: Int
    var name: String
    var viewContent: AnyView
}

And then in your view class(test), create an array of ViewList structure:

var views = [ViewsList.init(id: 1, name: "Example", viewContent: AnyView(AVExample())), ViewsList.init(id: 2, name: "ColorPicker", viewContent: AnyView(ColorPicker()))]

Then you can loop over this array as below :

NavigationView {
            List (views, id: \.id){ view in
                
             NavigationLink(
                  destination: view.viewContent,
                  label: {
                        Text("\(view.name)")
             })
  }
1
Jmcg On

Many thanks for the replies. I came up with the following solution which seems to work well.

private struct aView {
    var id = UUID()
    var view: AnyView
    var label: String
}

private var views = [
    aView(view: AnyView(AppStorageExample()), label: "App Storage"),
    aView(view: AnyView(AppStoreRecommend()), label: "App Store Recommended"),
    aView(view: AnyView(AVExample()), label: "AV Player"),
    aView(view: AnyView(ColorPickerExample()), label: "Color Picker"),
]

var body: some View {
        List (views, id: \.id) { view in
            NavigationLink(
                destination: view.view,
                label: {
                    Text("\(view.label)")
                })
        }

}