SwiftUI-布局-ForEach

注意点:

  1. 添加 id
  2. 需要索引的使用count

直接对数据循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private struct NamedFont: Identifiable {
let name: String
let font: Font
var id: String { name }
}

private let namedFonts: [NamedFont] = [
NamedFont(name: "Large Title", font: .largeTitle),
NamedFont(name: "Title", font: .title),
NamedFont(name: "Headline", font: .headline),
NamedFont(name: "Body", font: .body),
NamedFont(name: "Caption", font: .caption)
]

var body: some View {
ForEach(namedFonts) { namedFont in
Text(namedFont.name)
.font(namedFont.font)
}
}

循环需要索引

1
2
3
ForEach(0 ..< list.count, id: .self){ index in
Text("\(list[index])")
}
1
2
3
4
5
VStack{
ForEach{
...
}
}
1
2
3
4
5
List{
ForEach{
...
}
}