使用RowContent和WithParentID,让OutlineGroup能够缩进
时间: 2024-05-06 12:20:46 浏览: 6
在使用OutlineGroup时,可以通过RowContent的indentation参数来实现缩进效果,同时使用WithParentID来指定子节点的父节点ID。
例如,以下代码实现了一个简单的嵌套列表:
```
struct ContentView: View {
let items = [
Item(id: 1, name: "Item 1", parentId: nil),
Item(id: 2, name: "Item 1.1", parentId: 1),
Item(id: 3, name: "Item 1.2", parentId: 1),
Item(id: 4, name: "Item 1.2.1", parentId: 3),
Item(id: 5, name: "Item 2", parentId: nil),
Item(id: 6, name: "Item 2.1", parentId: 5),
Item(id: 7, name: "Item 2.2", parentId: 5),
]
var body: some View {
List {
ForEach(items, id: \.id) { item in
if item.parentId == nil {
OutlineGroup(item, children: { child in
ForEach(getChildren(id: child.id), id: \.id) { child in
OutlineGroup(child) { grandChild in
Text(grandChild.name)
}
.padding(.leading)
}
}) { parent in
Text(parent.name)
}
}
}
}
}
func getChildren(id: Int) -> [Item] {
return items.filter { $0.parentId == id }
}
}
struct Item: Identifiable {
let id: Int
let name: String
let parentId: Int?
}
```
在上面的代码中,我们首先定义了一个Item结构体,其中包含了id、name和parentId三个属性。然后定义了一个包含多个Item的数组。
在body中,我们使用List和ForEach来渲染嵌套列表。首先遍历所有的Item,找到parentId为nil的根节点。然后使用OutlineGroup来渲染根节点及其子节点。在children参数中,我们使用getChildren函数获取当前节点的所有子节点,并使用ForEach和OutlineGroup来递归渲染所有子节点及其子节点。在每个子节点中,我们使用padding参数来实现缩进效果。最后,在parent参数中,我们显示当前节点的名称。
通过这种方式,我们可以轻松地实现嵌套列表的缩进效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)