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

SwiftUI中DisclosureGroup内List占用高度超出条目数如何解决?

解决SwiftUI中DisclosureGroup内List过度占用空间的问题

在macOS应用侧边栏使用DisclosureGroup时,默认List会自动拉伸填充可用空间,导致展开后挤压其他视图。要让List仅占用对应行数的高度,可通过以下两种方式实现:

方法一:自适应内容高度(推荐)

通过fixedSize让List根据内容自动调整高度,同时配合listStyle(.plain)取消默认侧边栏List的拉伸行为:

DisclosureGroup("one") {
    List(items1, id: \.self) { item in
        Text(item)
    }
    .listStyle(.plain)
    .fixedSize(horizontal: false, vertical: true)
}
.padding()

fixedSize(horizontal: false, vertical: true)表示水平方向保持填充父视图,垂直方向根据内容自适应高度;listStyle(.plain)避免了默认侧边栏样式的强制拉伸,让List能正常响应尺寸调整。

方法二:手动计算高度(精确控制)

如果需要精确控制高度,可以根据列表项数量乘以macOS SwiftUI List默认行高(36pt),设置frame(maxHeight:):

DisclosureGroup("one") {
    List(items1, id: \.self) { item in
        Text(item)
    }
    .frame(maxHeight: CGFloat(items1.count) * 36)
}
.padding()

若使用自定义行高,只需将36替换为你的自定义行高即可。

完整修改代码

import SwiftUI

struct TestView: View {
    var items1: [String] = ["One", "two", "three"]
    var items2: [String] = ["Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]

    var body: some View {
        DisclosureGroup("one") {
            List(items1, id: \.self) { item in
                Text(item)
            }
            .listStyle(.plain)
            .fixedSize(horizontal: false, vertical: true)
        }
        .padding()

        DisclosureGroup("two") {
            List(items2, id: \.self) { item in
                Text(item)
            }
            .listStyle(.plain)
            .fixedSize(horizontal: false, vertical: true)
        }
        .padding()

        Spacer()
    }
}

修改后,展开的List只会占用对应行数的高度,不会挤压其他DisclosureGroup的位置,符合Xcode侧边栏的交互效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:53:12