【问题标题】:How to pass ForEach parameters to a SwiftUI views?如何将 ForEach 参数传递给 SwiftUI 视图?
【发布时间】:2022-11-23 02:47:22
【问题描述】:

我尝试在 SwiftUI 中显示三个页面,让我们将它们命名为:

TopGroup.swift(一级页面,这里包括一些主要书籍) SubGroup.swift(二级页面,这里包括一些子书组) Detail.swift(第三级页面,这里显示每本书的详细信息)

我链接了 SubGroup.swiftDetail.swift 页面,但未能将 TopGroup.swift 链接到 SubGroup.swift。因为我不知道如何通过下标或其他方式传递参数或参数。

数据模型定义如下:

struct Top: Identifiable {
    let id = UUID()
    let name: String
    let group: [Group]
    subscript(_ groupIndex: Int) -> Group {
        return group[groupIndex]
    }
}

struct Group: Identifiable {
    let id = UUID()  
    let name: String 
    let books: [Book]  // which define the detail info of every book
}

RootGroup.swift的代码我是这样写的:

struct TopGroup: View {
    var body: some View {
        NavigationView {
            List {
                // here show top group name
                ForEach(top) { item in
                    NavigationLink {
                        SubGroup()  // here link to subgroup
                    } label: {
                        VStack {
                            Text(item.name)
                        }
                    }
                }
            }
        }
    }
}

SubGroup.swift 的代码如下:

struct SubGroup: View {    
    var body: some View {
        NavigationView {
            List {
            
            // here should be subgroup like group[0], group[1], group[2]...
                ForEach(group[0]) { item in
                    Section(header: Text("Books Category of \(item.name)")) {
                        
                        // here link to detail book info
                        ForEach(item.books) { bookItem in
                            NavigationLink {
                                Detail(book: bookItem)
                            } label: {
                                BookRow(book: bookItem)
                            }
                        }
                    }
                }
            }
            .navigationBarTitle(top[0].name, displayMode: .inline)
        }
    }
}

现在我很困惑如何将参数从TopGroup.swift 传递给SubGroup.swift,这样top 中的每个项目都可以链接到正确的页面。

非常感谢~~

【问题讨论】:

  • 难道你只需要将 item 传递给 SubGroup 吗?
  • 将项目作为参数传递。也摆脱了内部 NavigationView 大多数应用程序只需要一个选项卡视图和工作表是例外。尝试观看 Demystify SwiftUI

标签: ios arrays swift swiftui


【解决方案1】:

在 SubGroup 中定义一个常量,获取您的组数组或整个 Top 对象:

let item: Top

将对象传递给 SubGroup 视图:

SubGroup(item: item)

基本上,由于 SwiftUI 中的视图只是结构,您可以定义常量(或变量),并且会自动为您生成初始化程序。

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 2011-12-09
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多