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

如何在ScrollView中填充垂直空间?尝试用Spacer().containerRelativeFrame解决

解决ScrollView内文本垂直居中问题

当前代码中,ScrollView内的蓝色矩形下方,我们希望文本能在剩余可视空间里垂直居中,但原写法里的Spacer和maxHeight: .infinity无法生效——因为ScrollView的内容容器高度由子视图总和决定,不会自动拉伸填满可视区域。

原代码

struct ContentView: View {
    var body: some View {
        VStack {
            ScrollView {
                Rectangle()
                    .fill(.blue)
                    .frame(height: 200)
                
                VStack {
                    Spacer()
                    Text("I want this text to be vertically centered in the remaining space.")
                    Spacer()
                }
                .frame(maxHeight: .infinity)
                
            }
        }
        .padding()
    }
}

使用containerRelativeFrame的解决方案

containerRelativeFrame可以让视图基于父容器(此处为ScrollView的可视区域)的尺寸布局,刚好能解决这个问题。以下是两种实现方式:

方式一:直接让文本容器占满容器高度并居中

struct ContentView: View {
    var body: some View {
        VStack {
            ScrollView {
                Rectangle()
                    .fill(.blue)
                    .frame(height: 200)
                
                Text("I want this text to be vertically centered in the remaining space.")
                    .containerRelativeFrame(.vertical) { size, axis in
                        size
                    } alignment: .center
            }
        }
        .padding()
    }
}

方式二:配合Spacer使用(更灵活)

struct ContentView: View {
    var body: some View {
        VStack {
            ScrollView {
                Rectangle()
                    .fill(.blue)
                    .frame(height: 200)
                
                VStack {
                    Spacer()
                        .containerRelativeFrame(.vertical, count: 1, spacing: 0)
                    Text("I want this text to be vertically centered in the remaining space.")
                    Spacer()
                        .containerRelativeFrame(.vertical, count: 1, spacing: 0)
                }
            }
        }
        .padding()
    }
}

说明

containerRelativeFrame(.vertical)会让Spacer(或文本视图)的高度基于ScrollView的可视剩余高度分配,两个Spacer各占一半空间,就能让文本完美居中。这种方案是当前解决ScrollView内剩余空间布局的最优方式之一,它直接关联容器的可视尺寸,避开了ScrollView内容高度自适应的限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:52:14