ios - SwiftUI 中默认展开的 List 或 OutlineGroup
问题描述
使用 SwiftUI 中的 List 或 OutlineGroup 如何在创建视图时使其部分(或全部)分支默认展开。这似乎可以通过具有绑定的 DisclosureGroup 实现。
这对于恢复状态或自定义视图以进行演示很有用。
解决方案
的可重用版本OutlineGroup
,可扩展性受到控制。
import SwiftUI
struct NodeOutlineGroup<Node>: View where Node: Hashable, Node: Identifiable, Node: CustomStringConvertible{
let node: Node
let childKeyPath: KeyPath<Node, [Node]?>
@State var isExpanded: Bool = true
var body: some View {
if node[keyPath: childKeyPath] != nil {
DisclosureGroup(
isExpanded: $isExpanded,
content: {
if isExpanded {
ForEach(node[keyPath: childKeyPath]!) { childNode in
NodeOutlineGroup(node: childNode, childKeyPath: childKeyPath, isExpanded: isExpanded)
}
}
},
label: { Text(node.description) })
} else {
Text(node.description)
}
}
}
struct ContentView: View {
var body: some View {
List {
NodeOutlineGroup(node: data, childKeyPath: \.children, isExpanded: true)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct FileItem: Hashable, Identifiable, CustomStringConvertible {
var id: Self { self }
var name: String
var children: [FileItem]? = nil
var description: String {
switch children {
case nil:
return " \(name)"
case .some(let children):
return children.isEmpty ? " \(name)" : " \(name)"
}
}
}
let data =
FileItem(name: "users", children:
[FileItem(name: "user1234", children:
[FileItem(name: "Photos", children:
[FileItem(name: "photo001.jpg"),
FileItem(name: "photo002.jpg")]),
FileItem(name: "Movies", children:
[FileItem(name: "movie001.mp4")]),
FileItem(name: "Documents", children: [])
]),
FileItem(name: "newuser", children:
[FileItem(name: "Documents", children: [])
])
])
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
推荐阅读
- macros - nom 的 "$i" 宏参数从何而来?
- elasticsearch - 使用 go 在 elasticsearch 中进行大规模更新
- java - 在 Criteria API 中按目标加入
- r - 使用函数 filter() 计算移动平均值时出现“无适用方法”错误
- vba - 以编程方式插入构建基块时出现自动化错误 Word 2016
- javascript - 手动更新 redux 状态时更改了 redux 状态引用
- sql-server - 同一张表上分组行的差异和百分比变化
- css - Angular6 - 如何根据移动设备和浏览器改变 .css 类的宽度
- html - 如何最小化 html 表格中的列宽?
- sql-server - 在表值函数中声明变量