在SwiftUI中绑定到ForEach [英] Binding in a ForEach in SwiftUI
本文介绍了在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文