簡體   English   中英

SwiftUI中通過多個View綁定一個Array

[英]Binding an Array through multiple Views in SwiftUI

我被這個問題困住了。 我有以下從@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 有一個編輯按鈕,可以在 AppleSummary 和 AppleEditor 之間切換,所以這里將修改蘋果。

struct AppleDetail: View {

    @Binding var apple: Apple

    var body: some View {
        ...
    }
}

AppleRow 不需要修改蘋果。

struct AppleRow: View {

    var apple: Apple

    var body: some View {
        ...
    }
}

問題出在 ForEach 循環中:如何從元素的綁定數組中創建一個綁定元素,當它們被修改時會將修改發送到 AppleList 的父級?

解決方案很簡單:

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