【问题标题】:Two ForEach in SwiftUISwiftUI 中的两个 ForEach
【发布时间】:2019-09-28 13:02:29
【问题描述】:

我想在 SwiftUI 中创建两个循环。例如:

ForEach (chapterData) { chapter in

  ForEach (chapter.line) { line in 

     Text("\(line.text)")
  }
}

chapterData 是一个章节表( [Chapter] ):

struct Chapter: Codable, Identifiable { 
  let id:Int
  let line:[Line] 
} 

struct Line: Codable, Identifiable {
  let id: Int
  let text: String 
} 

我想获取chapterData中所有章节的line.text

但我无法编译这段代码,我认为不可能以这种方式执行两个 ForEach 循环。

有人可以帮我吗?

【问题讨论】:

  • 是的,我刚刚添加了

标签: swift swiftui swiftui-list


【解决方案1】:

我已更改您的章节 - 最好为任何 Collection 使用复数名称,因为它可以提高代码的可读性:

struct Chapter: Codable, Identifiable {
  let id:Int
  let lines: [Line]
}

您的 ForEach 语法存在问题,您的第二个 ForEach 应该将 chapter.lines 作为其参数,因为这是实际列表。将外部 ForEach 包裹在 VStackList 中也很重要。因此,您的视图主体可能如下所示:

var body: some View {
        VStack {
            ForEach(chapterData) { chapter in
                ForEach(chapter.lines) { line in
                    Text(line.text)
                }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多