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

SwiftUI实现VStack布局:首尾固定高度,中间子视图占剩余空间

SwiftUI实现VStack固定+自适应高度布局

在SwiftUI中实现这种布局非常直接,核心是利用视图修饰符让中间元素自动填充剩余垂直空间,同时确保外层容器能获取父视图的全部可用高度。

完整代码示例

struct ContentView: View {
    var body: some View {
        VStack(spacing: 10) { // 可根据需求调整子视图间距
            // 顶部固定高度视图
            Text("顶部固定区域")
                .frame(height: 80) // 设置固定高度
                .background(Color.blue)
                .foregroundColor(.white)
            
            // 中间自适应剩余高度视图
            Text("中间填充剩余空间")
                .frame(maxHeight: .infinity) // 关键:占据所有可用剩余高度
                .background(Color.yellow)
            
            // 底部固定高度视图
            Text("底部固定区域")
                .frame(height: 60) // 设置固定高度
                .background(Color.red)
                .foregroundColor(.white)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity) // 让VStack占满屏幕可用空间
        // 可选:若需要忽略安全区,添加下面一行
        // .edgesIgnoringSafeArea(.all)
    }
}

关键逻辑说明

  • 外层VStack必须通过.frame(maxWidth: .infinity, maxHeight: .infinity)声明自己要占据父视图的全部空间,否则中间视图无法获取剩余高度。
  • 中间视图使用.frame(maxHeight: .infinity)修饰符,该修饰符会让视图自动填充当前容器内的所有剩余垂直空间,完美适配不同设备的屏幕尺寸。
  • 顶部和底部视图直接用.frame(height: xxx)设置固定高度,数值可根据业务需求自由修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:12:00