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

如何设置启动时List的所有Section默认处于折叠状态

SwiftUI List静态Section默认全部折叠解决方案

适配iOS 16+ 方案(原生Section折叠API)

无需嵌套数组构造数据源,直接给每个静态Section绑定独立的展开状态变量,默认设为false即可实现默认折叠:

  1. 声明各Section对应展开状态
@State private var section1Expanded = false
@State private var section2Expanded = false
// 有N个静态Section就声明N个对应状态变量
  1. 替换原List代码
List {
    Section("Section 1 标题", expanded: $section1Expanded) {
        // 此处放Section 1的静态内容
        Text("内容行1")
        Text("内容行2")
    }
    Section("Section 2 标题", expanded: $section2Expanded) {
        // 此处放Section 2的静态内容
        Text("内容行1")
        Text("内容行2")
    }
}
.listStyle(.grouped)

兼容iOS 15及更低版本方案

用DisclosureGroup实现折叠效果,同样不需要嵌套数组:

@State private var section1Expanded = false
@State private var section2Expanded = false

var body: some View {
    List {
        Section {
            DisclosureGroup("Section 1 标题", isExpanded: $section1Expanded) {
                // Section 1静态内容
                Text("内容行1")
                Text("内容行2")
            }
        }
        Section {
            DisclosureGroup("Section 2 标题", isExpanded: $section2Expanded) {
                // Section 2静态内容
                Text("内容行1")
                Text("内容行2")
            }
        }
    }
    .listStyle(.grouped)
}

注意事项

  • 所有展开状态变量默认值设为false即可实现初始全部折叠,无需额外逻辑
  • 可根据设计需求替换listStyle参数,.insetGrouped、.sidebar等样式均支持折叠交互
  • 所有Section完全静态声明,不需要构造嵌套数组类型的数据源,符合使用需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:27:03