【问题标题】:ForEach loop in Swift to use content of 2D arraySwift 中的 ForEach 循环使用二维数组的内容
【发布时间】:2021-11-30 01:44:57
【问题描述】:

我想使用 ForEach 循环,但它不起作用。

let navigation = [["Kunde", "person"], ["Wartung", "gear"]]


NavigationView {
    List {
        NavigationLink(destination: ListView(title: "Kunde")) {
            Label("Kunde", systemImage: "person")
        }
        NavigationLink(destination: ListView(title: "Wartung")) {
            Label("Wartung", systemImage: "gear")
        }
        // MANY MORE
    }
}

我的方法打印从 0 到 7 的数字,但我想要数组的内容。

我的做法:

let navigation = [["Kunde", "person"], ["Wartung", "gear"]]


NavigationView {
    List {
        ForEach(navigation.indices) { index in
            NavigationLink(destination: ListView(title: "\(index)")) {
                Label("\(self.index)", systemImage: "\(index)")
            }
        }
    }
}

【问题讨论】:

    标签: foreach swiftui


    【解决方案1】:

    您只提供index。例如,您可以使用navigation[index][0] 来获取标题,但这很乏味。

    更好的方法是创建一个自定义类型,而且它也将是Identifiable,因此在可变的项目列表中使用它更安全。

    代码:

    struct ContentView: View {
        private let navigation = [
            NavigatableView("Kunde", image: "person"),
            NavigatableView("Wartung", image: "gear")
        ]
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(navigation) { newView in
                        NavigationLink(destination: ListView(title: newView.title)) {
                            Label(newView.title, systemImage: newView.image)
                        }
                    }
                }
            }
        }
    }
    
    struct NavigatableView: Identifiable {
        let id = UUID()
        let title: String
        let image: String
    
        init(_ title: String, image: String) {
            self.title = title
            self.image = image
        }
    }
    

    【讨论】:

    • 我会坚持你的第一个版本,因为它更短。谢了!
    • @Nikolass 更短的代码并不意味着更好的代码。如果您更改 navigation,您将遇到动画问题,因为您是通过索引而不是唯一标识符进行识别。这也不是特别安全,因为这些数组的大小可能无法预测。
    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2015-08-02
    • 1970-01-01
    • 2017-07-07
    • 2014-09-12
    相关资源
    最近更新 更多