SwiftUI LazyVGrid内DisclosureGroup展开时重叠问题如何解决
问题原因分析
- 你在
ContentView中给DisclosureGroupView硬编码了固定高度.frame(height: 80),无论内部DisclosureGroup是否展开,整个组件的高度被限制死,超出80的内容自然会溢出,和下方元素重叠。 DisclosureGroupView内部使用的GeometryReader默认不会自适应子内容高度,它会优先填充父视图分配的空间,无法跟随内部展开的内容动态调整自身高度。- 你尝试的
zIndex仅能控制视图的层级显示,无法改变容器的实际高度,自然没法实现把下方内容往下推的效果。
修复方案
按照以下步骤修改即可实现展开时自动撑开容器,推挤下方内容的效果:
- 移除
ContentView中DisclosureGroupView的固定高度约束 - 去掉
DisclosureGroupView内部的GeometryReader,改用自适应的GridItem布局,让LazyVGrid可以自动计算整体高度 - 可根据需求调整DisclosureGroup的宽度约束,避免和网格列宽冲突
完整修改后的代码
DisclosureGroupView代码
struct DisclosureGroupView: View { var groups: [String: [String]] @State private var isExpanded: [String: Bool] @State private var selectedItems = [String: Set<String>()] @State private var isTitleChecked: [String: Bool] init(groups: [String: [String]]) { self.groups = groups _isExpanded = State(initialValue: groups.reduce(into: [String: Bool](), { result, group in result[group.key] = false })) _isTitleChecked = State(initialValue: groups.reduce(into: [String: Bool](), {result, group in result[group.key] = false })) } var body: some View { // 移除GeometryReader,改用自适应网格布局 let layout = Array(repeating: GridItem(.flexible(), spacing: 5), count: 2) LazyVGrid(columns: layout, alignment: .leading, spacing: 8) { ForEach(groups.keys.sorted(), id: \.self) { title in self.disclosureGroup(title: title, items: groups[title, default: [String]()]) } } } private func disclosureGroup(title: String, items: [String]) -> some View { let expanded = Binding<Bool>(get: {isExpanded[title]!}, set: {isExpanded[title] = $0}) return DisclosureGroup(title, isExpanded: expanded) { ScrollView { VStack(alignment: .leading) { ForEach(Array(items.enumerated()), id: \.1.hashValue) { index, item in Text(item) .frame(maxWidth: .infinity, alignment: .leading) } } } .frame(height: 60) } .font(.body) .frame(maxWidth: .infinity) .accentColor(.white) .foregroundColor(.white) .padding(5) .background(Color(UIColor.systemBlue)) .cornerRadius(8.0) } }
ContentView代码
struct ContentView: View { var body: some View { VStack(alignment: .center, spacing: 10) { Text("Disclosure Groups") let groups: [String: [String]] = ["R1C1" : ["item 1", "item 2", "item 3", "item 4"], "R1C2" : ["item 3", "item 4", "item 6", "item 7"], "R2C1" : ["item 5", "item 6"], "R2C2" : ["item 7", "item 8"]] // 移除固定高度约束 DisclosureGroupView(groups: groups) Text("More Text here that is long") .padding() Text("Some More Text even wider than the first one") } .padding(.horizontal, 16) } }
补充说明
如果需要保留每行DisclosureGroup的固定宽度,也可以把GridItem的flexible改成fixed对应宽度,只要去掉固定高度约束,LazyVGrid依然会自动跟随展开内容调整整体高度,不会出现重叠问题。
内容的提问来源于stack exchange,提问作者RXP
相关产品推荐
相关产品推荐

