2

I want to pass a View ("MarketsListView" or "ProductsListView") as a var on struct ("ConfigItem"), this views has different info, buttons, etc. What is the best way? Thanks.

Edit: obviously the current code has errors, I'm stuck there.

import SwiftUI

struct ConfigItem {
    var label: String
    var view: AnyView?
}

var configItems: [ConfigItem] = [
    ConfigItem(label: "Markets", view: MarketsListView),
    ConfigItem(label: "Products", view: ProductsListView)
]

struct ConfigView: View {
    var body: some View {
        NavigationView {
            Form {
                List(configItems, id: \.label) { configItem in
                    NavigationLink(destination: configItem.view) {
                        Text(configItem.label)
                    }
                }
            }
            .navigationBarTitle("Configuration")
        }
    }
}

struct ConfigView_Previews: PreviewProvider {
    static var previews: some View {
        ConfigView()
    }
}

1 Answers1

1

Here is fixed part

struct ConfigItem {
    var label: String
    var view: AnyView
}

var configItems: [ConfigItem] = [
    ConfigItem(label: "Markets", view: AnyView(MarketsListView())),
    ConfigItem(label: "Products", view: AnyView(ProductsListView()))
]

Also you can consider generic approach in this answer SwiftUI - how to avoid navigation hardcoded into the view?

Asperi
  • 228,894
  • 20
  • 464
  • 690