You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程默认展开SwiftUI List的所有子项?

SwiftUI List 默认展开所有层级子项的实现方案

当子项层级数量不确定时,没法直接用DisclosureGroup,可以通过递归数据模型+递归视图的方式实现默认全展开的列表,具体实现如下:

1. 定义带展开状态的递归数据模型

给每个节点添加isExpanded属性,初始化时直接设为true,确保所有节点默认展开:

struct ListNode: Identifiable {
    let id = UUID()
    let title: String
    var children: [ListNode]
    var isExpanded: Bool
}

2. 实现递归列表视图

通过递归调用视图,自动处理任意层级的子项,仅当节点展开且存在子项时渲染子列表:

struct ExpandingListItem: View {
    var node: ListNode
    
    var body: some View {
        Text(node.title)
        if node.isExpanded && !node.children.isEmpty {
            List(node.children) { child in
                ExpandingListItem(node: child)
            }
            .listStyle(.plain)
        }
    }
}

3. 使用示例

构造任意层级的测试数据,直接引入递归视图即可:

struct ContentView: View {
    let data: [ListNode] = [
        ListNode(title: "文件夹A", children: [
            ListNode(title: "子文件夹A1", children: [
                ListNode(title: "文件A1-1", children: [], isExpanded: true)
            ], isExpanded: true),
            ListNode(title: "文件A2", children: [], isExpanded: true)
        ], isExpanded: true),
        ListNode(title: "文件夹B", children: [], isExpanded: true)
    ]
    
    var body: some View {
        List(data) { node in
            ExpandingListItem(node: node)
        }
        .listStyle(.insetGrouped)
    }
}

核心说明

  • 递归模型的isExpanded属性是实现默认全展开的核心,初始化时设为true即可生效
  • 递归视图会自动遍历所有层级的子项,无论层级深度如何都能正确渲染
  • 子列表使用.plain样式,可避免嵌套时出现重复的分组边框,保持整体视觉统一

内容的提问来源于stack exchange,提问作者JackS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:22:22