在SwiftUI中,可以使用List
视图来创建列表。要创建分组列表,只需在List
中使用ForEach
控件将项目分组,并使用Section
视图包装它们。
以下是一个示例代码,它创建一个分组列表,其中有两个组,每个组中有三个项目。其中,第一组的标题为“Group 1”,第二组的标题为“Group 2”:
struct ContentView: View {
let items = ["Item 1", "Item 2", "Item 3"]
var body: some View {
List {
Section(header: Text("Group 1")) {
ForEach(items, id: \.self) { item in
Text(item)
}
}
Section(header: Text("Group 2")) {
ForEach(items, id: \.self) { item in
Text(item)
}
}
}
}
}
要将新的分组插入到分组列表中,只需在List
中添加一个新的Section
即可。以下是一个示例代码,它将一个新的空分组插入到列表的末尾:
struct ContentView: View {
var groups = ["Group 1", "Group 2"]
let items = ["Item 1", "Item 2", "Item 3"]
var body: some View {
List {
ForEach(groups, id: \.self) { group in
Section(header: Text(group)) {
ForEach(items, id: \.self) { item in
Text(item)
}
}
}
// Insert a new empty section at the end of the list
Section(header: Text("New Group")) {
Text("Empty")
}
}
}
}