如何使用动态视图名称创建SwiftUI导航链接列表

时间:2020-07-17 12:07:40

标签: swiftui navigationlink

我试图创建一个简单的视图列表供用户访问,但我不知道如何用数组变量替换视图名称。在以下目标示例中:硬编码为AVExample(),这是我的视图之一,但是如何使用数组中的名称?

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 个答案:

答案 0 :(得分:0)

您可以为视图创建一个结构,然后使用该结构数组。例如:

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

然后在您的视图类(测试)中,创建一个ViewList结构数组:

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

然后您可以如下遍历此数组:

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

答案 1 :(得分:0)

非常感谢您的答复。我想出了以下似乎很有效的解决方案。

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

}