0

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)")
                    })
            }
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
Jmcg
  • 239
  • 2
  • 9
  • Static type checking will not allow you to do that, instead you can use approach similar to [provided here](https://stackoverflow.com/a/62950510/12299030) – Asperi Jul 17 '20 at 12:12
  • Why Don't you use a Dictionary instead? ["AVExample": AVExample(), "ColorPickerExample": ColorPickerExample(), "DatePickerExample": DatePickerExample()] – Renata Faria Jul 17 '20 at 12:56

2 Answers2

0

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)")
             })
  }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Anjali Aggarwal
  • 611
  • 4
  • 8
0

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

}

Jmcg
  • 239
  • 2
  • 9