简体   繁体   English

SwiftUI中通过多个View绑定一个Array

[英]Binding an Array through multiple Views in SwiftUI

I'm stuck with this problem.我被这个问题困住了。 I've the following struct that builds a List from a @Binding Array我有以下从@Binding Array 构建 List 的结构

struct AppleList: View {

    @Binding var apples: [Apple]

    var body: some View {
        NavigationView {
            List {
                ForEach(apples) { apple  in
                    NavigationLink(destination: AppleDetail(apple: $apple)) {
                        AppleRow(apple: apple)
                    }
                }
            }
        }
    }
}

AppleDetail has an edit button that switches between AppleSummary and AppleEditor, so here the apple will be modified. AppleDetail 有一个编辑按钮,可以在 AppleSummary 和 AppleEditor 之间切换,所以这里将修改苹果。

struct AppleDetail: View {

    @Binding var apple: Apple

    var body: some View {
        ...
    }
}

AppleRow doesn't need to modify apple. AppleRow 不需要修改苹果。

struct AppleRow: View {

    var apple: Apple

    var body: some View {
        ...
    }
}

The problem is in the ForEach loop: how can make a binding element from a binding array of elements that when they will be modified will send the modification to the parent of AppleList?问题出在 ForEach 循环中:如何从元素的绑定数组中创建一个绑定元素,当它们被修改时会将修改发送到 AppleList 的父级?

Solution was quite simple:解决方案很简单:

ForEach(apples.indices) { idx in
    NavigationLink(destination: AppleDetail(transaction: self.$apples[idx])) {
        AppleRow(transaction: apples[idx])
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM