SwiftUI 如何修改List可折叠Section箭头图标及设置默认折叠状态
方案说明
1. 自定义可折叠Section箭头最优方案
SidebarListStyle 下系统自带的 Section 折叠箭头是私有控件,没有公开的修改接口,最优解是用 DisclosureGroup 完全接管折叠逻辑,完全自定义头部视图和箭头样式,不会受系统版本迭代影响,适配性最高。
具体实现逻辑:
- 放弃系统自带的 Section 折叠能力,将 Section 内部的列表内容包裹在
DisclosureGroup中 - 自定义
DisclosureGroup的 label 视图,直接复用你已有的Header组件,额外添加自定义箭头图标,根据展开状态控制图标旋转即可 - 该方案可以完全控制箭头的图标、大小、颜色、位置,不受系统默认样式限制
2. 设置Section默认折叠状态
上面的方案天然支持默认折叠配置,你只需要自行维护每个Section对应的 isExpanded 状态,默认赋值为 false 就是折叠状态,赋值为 true 就是默认展开。
适配后的代码示例
// 新增:维护每个分组的展开状态,默认false即默认折叠 @State private var expandStates: [String: Bool] = [:] // 你的原有视图代码 VStack(alignment: .leading, spacing: 0) { List { ForEach(Array(self.dict!.keys.sorted()), id: \.self) { key in if let tasks = self.dict![key] { Section { // 用DisclosureGroup接管折叠逻辑 DisclosureGroup(isExpanded: $expandStates[key, default: false]) { // 原有cell内容 ForEach(Array(tasks.enumerated()), id:\.1.title) { (index, task) in VStack(alignment: .leading, spacing: 40) { PillForRow(index: index, task: task) .padding(.bottom, 40) }.onTapGesture { self.selectedTask = task } } } label: { // 自定义头部,替换系统默认带箭头的header HStack { Header(title: key, SubtitleText: Text(""), showTag: true, tagValue: tasks.count) Spacer() // 自定义箭头图标,可任意修改样式 Image(systemName: "chevron.down") .rotationEffect(.degrees(expandStates[key, default: false] ? 0 : -90)) } .background(Color.white) } } .listRowInsets(inset) .textCase(nil) } } if let completedTasks = tasks.filter {$0.state == .Completed} { Section { DisclosureGroup(isExpanded: $expandStates["completed", default: false]) { ForEach(Array(completedTasks.enumerated()), id:\.1.title) { (index, task) in PillForRow(index: index, task: task) } } label: { HStack { Header(title: "Completed", SubtitleText: Text(""), showTag: true, tagValue: completedTasks.count) Spacer() Image(systemName: "chevron.down") .rotationEffect(.degrees(expandStates["completed", default: false] ? 0 : -90)) } .background(Color.white) } } .listRowInsets(inset) .textCase(nil) } } .listStyle(SidebarListStyle()) }
注意事项
- 如果不需要显示箭头,直接删除label里的Image相关代码即可,点击整个头部区域仍然可以触发折叠展开
- 可以替换
Image(systemName: "chevron.down")为任意自定义图标,实现完全个性化的样式
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

