【问题标题】:Binding in a ForEach in SwiftUI在 SwiftUI 中的 ForEach 中绑定
【发布时间】:2021-01-29 22:12:24
【问题描述】:

我使用FetchRequest 来填充元素。然后我正在使用一个列表并希望显示某种待办事项元素,您可以在其中看到哪个被选中,哪个未被选中。为此我创建了一个 CheckBoxView。

我现在的问题是,我需要将绑定传递给视图。但是如何在 ForEach 中做到这一点? 如果我有一个对我来说很容易的绑定,我只需生成一个@State 就可以了。这里怎么做?

List {
    ForEach(elements, id: \.self) { item in
        CheckBoxView(checked: item.checked)
    }
}

这里是视图:

struct CheckBoxView: View {
    @Binding var checked: Bool
    ....
}

【问题讨论】:

    标签: swift foreach binding swiftui fetchrequest


    【解决方案1】:

    假设你的 elements 是 items 数组的状态,它可以是

    List {
        ForEach(elements.indices, id: \.self) { i in
            CheckBoxView(checked: $elements[i].checked)
        }
    }
    

    【讨论】:

    • 您能解释一下为什么要使用索引吗?
    猜你喜欢
    • 2022-01-15
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多