SwiftUI如何创建分组和插入分组列表?

8 min read

在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")
            }
        }
    }
}