本文介绍了在 SwiftUI 中绑定 ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 FetchRequest
来填充元素.然后我使用一个列表并希望显示某种待办事项元素,您可以在其中查看哪些已选中,哪些未选中.为此我创建了一个 CheckBoxView.
I use a FetchRequest
to fill the elements. 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.
我现在的问题是,我需要将绑定传递给视图.但是如何在 ForEach 中做到这一点?如果我有一个单一的绑定对我来说很容易,我只需生成一个 @State
并且它可以工作.这里怎么做?
My problem now is, that I need to pass a binding to the view. But how to do that in the ForEach?If I have a single binding its easy for me, I just generate a @State
and it works. How to do it here?
List {
ForEach(elements, id: .self) { item in
CheckBoxView(checked: item.checked)
}
}
这是视图:
struct CheckBoxView: View {
@Binding var checked: Bool
....
}
推荐答案
假设你的 elements
是 items 数组的状态,它可以是
Assuming your elements
is state of items array, it can be
List {
ForEach(elements.indices, id: .self) { i in
CheckBoxView(checked: $elements[i].checked)
}
}
这篇关于在 SwiftUI 中绑定 ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!