[英]Binding in a ForEach in SwiftUI
I use a FetchRequest
to fill the elements.我使用
FetchRequest
来填充元素。 Then I'm using a list and want to display some kind of todo elements where you see which one is checked and which one not.然后我使用一个列表并希望显示某种待办事项元素,您可以在其中查看哪些已选中,哪些未选中。 Therefor I created a CheckBoxView.
为此我创建了一个 CheckBoxView。
My problem now is, that I need to pass a binding to the view.我现在的问题是,我需要将绑定传递给视图。 But how to do that in the ForEach?
但是如何在 ForEach 中做到这一点? If I have a single binding its easy for me, I just generate a
@State
and it works.如果我有一个单一的绑定对我来说很容易,我只需生成一个
@State
并且它可以工作。 How to do it here?这里怎么做?
List {
ForEach(elements, id: \.self) { item in
CheckBoxView(checked: item.checked)
}
}
Here is the view:这是视图:
struct CheckBoxView: View {
@Binding var checked: Bool
....
}
Assuming your elements
is state of items array, it can be假设你的
elements
是 items 数组的状态,它可以是
List {
ForEach(elements.indices, id: \.self) { i in
CheckBoxView(checked: $elements[i].checked)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.