带有@Binding 控件的 SwiftUI 动态列表 [英] SwiftUI dynamic List with @Binding controls
本文介绍了带有@Binding 控件的 SwiftUI 动态列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用@Binding 驱动的控件构建动态列表,而无需手动引用数组?看起来很明显,但是使用 List 或 ForEach 遍历数组会产生各种奇怪的错误.
struct OrderItem : 可识别 {让 id = UUID()变量标签:字符串无功值:布尔=假}结构内容视图:查看{@State var items = [OrderItem(label: "Shirts"),订单项(标签:裤子"),订单项(标签:袜子")]var主体:一些视图{导航视图{形式 {部分 {列表 {切换(items[0].label, isOn: $items[0].value)切换(项目[1].标签,isOn:$项目[1].值)切换(项目[2].标签,isOn:$项目[2].值)}}}.navigationBarTitle("服装")}}}
这不起作用:
<代码> ...部分 {List($items, id: \.id) { item in切换(item.label, isOn: item.value)}}...
<块引用>
类型_"没有成员id"
也没有:
<代码> ...部分 {List($items) { item in切换(item.label, isOn: item.value)}}...
<块引用>
无法推断通用参数SelectionValue"
解决方案
尝试类似的事情
<代码>...部分 {列表(items.indices){ 索引切换(self.items[index].label, isOn: self.$items[index].value)}}...
How do I build a dynamic list with @Binding-driven controls without having to reference the array manually? It seems obvious but using List or ForEach to iterate through the array give all sorts of strange errors.
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")
}
}
}
This doesn't work:
...
Section {
List($items, id: \.id) { item in
Toggle(item.label, isOn: item.value)
}
}
...
Type '_' has no member 'id'
Nor does:
...
Section {
List($items) { item in
Toggle(item.label, isOn: item.value)
}
}
...
Generic parameter 'SelectionValue' could not be inferred
解决方案
Try something like
...
Section {
List(items.indices) { index in
Toggle(self.items[index].label, isOn: self.$items[index].value)
}
}
...
这篇关于带有@Binding 控件的 SwiftUI 动态列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文