首页 > 解决方案 > 带有 @Binding 控件的 SwiftUI 动态列表

问题描述

如何使用@Binding 驱动的控件构建动态列表,而无需手动引用数组?这似乎很明显,但使用 List 或 ForEach 遍历数组会产生各种奇怪的错误。

struct OrderItem : Identifiable {
    let id = UUID()
    var label : String
    var value : Bool = false
}

struct ContentView: View {
    @State var items = [OrderItem(label: "Shirts"),
                        OrderItem(label: "Pants"),
                        OrderItem(label: "Socks")]
    var body: some View {
        NavigationView {
            Form {
                Section {
                    List {
                        Toggle(items[0].label, isOn: $items[0].value)
                        Toggle(items[1].label, isOn: $items[1].value)
                        Toggle(items[2].label, isOn: $items[2].value)
                    }
                }
            }.navigationBarTitle("Clothing")
        }
    }
}

这不起作用:

            ...
                Section {
                    List($items, id: \.id) { item in
                        Toggle(item.label, isOn: item.value)
                    }
                }
            ...

类型“_”没有成员“id”

也没有:

            ...
                Section {
                    List($items) { item in
                        Toggle(item.label, isOn: item.value)
                    }
                }
            ...

无法推断通用参数“SelectionValue”

标签: swiftuicombineswiftui-list

解决方案


尝试类似的东西

...
   Section {
       List(items.indices) { index in
           Toggle(self.items[index].label, isOn: self.$items[index].value)
       }
   }
...

推荐阅读