如何在 swiftUI 中显示数组的数组

TJM*_*Mac 0 arrays foreach swiftui

在膳食计划应用程序中,用户选择一周中每一天所需的项目,从而为每天创建一系列项目。然后将这些数组插入到购物清单数组中,创建包含所有商品的数组数组。

我一直试图显示合并列表。在我的代码中,我正确返回了数组的计数,但是当我尝试显示每个数组中的项目时,我失败了。任何帮助,将不胜感激!

这是我正在尝试做的事情的简化示例:

import SwiftUI

struct ShoppingListView: View {
    
    var shoppingList: Array<Array<String>>

    
    var body: some View {
        VStack(alignment: .leading) {
            ForEach(0..<shoppingList.count, id: \.self) {list in
                Text("number of arrays")
                VStack {
                    List(0..<list) { item in
                        Text("item = \(item)")
                    }
                }
            }
        }
    }
}

struct ShoppingListView_Previews: PreviewProvider {
    static var previews: some View {
        let list = [["eggs", "bread", "milk", "cheese" ],["steak", "potatoes", "salad kit"]]
        ShoppingListView(shoppingList: list)
    }
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 5

首先,较新的使用0..<shoppingList.countinsideForEachList,因为在您更改项目计数的那一天,您将面临列表未更新的问题,就像在本中一样。shoppingList.indices代替使用。

您正在枚举索引,但看起来您希望在块中获取一个项目。这不会发生。

完美地为您的项目创建struct并使其符合Identifiable,然后您就可以调用ForEach(shoppingList) {并在块中获取您的项目。

在此之前,您可以毫无问题地使用枚举索引,只需从列表中按索引获取项目即可:

var shoppingList: Array<Array<String>> = [["eggs", "bread", "milk", "cheese" ],["steak", "potatoes", "salad kit"]]

var body: some View {
    VStack(alignment: .leading) {
        ForEach(shoppingList.indices, id: \.self) { i in
            Text("number of arrays")
            let sublist = shoppingList[i]
            VStack {
                List(sublist.indices, id: \.self) { j in
                    Text("item = \(sublist[j])")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)