swiftui - 带有 @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”
解决方案
尝试类似的东西
...
Section {
List(items.indices) { index in
Toggle(self.items[index].label, isOn: self.$items[index].value)
}
}
...
推荐阅读
- android - Android:播放服务广告的问题
- python - Django 制作动态删除功能
- java - 403 spring-boot-2-keycloak-适配器
- wordpress - 联系 7 Form Wordpress 如何从自定义 HTML 标签(td)中获取数据?
- jenkins - Drupal 网站的 CICD
- php - 如何清理被黑的 Drupal 站点
- css - 将样式应用于除第一种类型的元素之外的所有元素
- django - 在相关对象中批量创建
- google-signin - 谷歌登录谷歌助手的对话流程给出 500 内部服务器错误?
- webrtc - WebRTC 视频流错误 - scaledrone