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

SwiftUI中如何让Text所在容器占满空间并居中内容

SwiftUI 实现加载容器占满空间并内容居中

针对你的需求,需要调整外层ScrollView和内部容器的布局属性,同时优化加载状态下的VStack布局,具体修改如下:

关键修改点

  • 让ScrollView占满屏幕可用高度:添加.frame(maxHeight: .infinity)
  • 让ZStack填充ScrollView的全部空间:添加.frame(maxWidth: .infinity, maxHeight: .infinity)
  • 简化加载状态下的VStack布局,通过frame和alignment属性直接实现内容居中,无需冗余的Spacer

修改后的完整代码

ScrollView {
    //MARK -Please make this zstack take entire visible space height
    ZStack {
        VStack(spacing:0) {
            HStack{
                Image("Diagnostic")
                    .resizable()
                    .frame(width: 23, height: 23)
                    .foregroundColor(Color(ViewControllerCosntants.secondaryColor700))
                Text("Diagnosis")
                    .font(.custom(ViewControllerCosntants.robotoRegular, size: 26))
                    .foregroundColor(Color(ViewControllerCosntants.secondaryColor700))
                    .padding(.leading, 16)
            }
            .frame(width: UIScreen.main.bounds.width - 50, alignment: .leading)
            .padding(EdgeInsets(top: 20, leading: 25, bottom: 15, trailing: 25))

            IconButton(iconName: "Share", title: "Share", description: $description)
                .padding(.bottom, 28)
                .onTapGesture {
                    ShareDiagnostic()
                }

            Divider()
                .frame(width: UIScreen.main.bounds.width, height: 3)
                .overlay(Color("PrimaryColor"))
                .padding(EdgeInsets(top: 0, leading: 25, bottom: 0, trailing: 25))

            if(loading) {
                // 优化后的加载容器布局
                VStack(alignment: .center, spacing: 15) {
                    Text("Loading diagnostic\n")
                    LottieView(loopMode: .loop)
                        .frame(width: 45, height: 45)
                        .padding(.vertical, 15)
                    Text("Commands pending \(diagnoseViewModel.numberOfCommandsPending)")
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .contentAlignment(.center) // iOS14+ 支持,确保内容居中
            } else {
                Text("The multi line text goes here.")
            }
        }
        .disabled(diagnoseViewModel.showLoading)
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity) // 让ZStack占满ScrollView空间
}
.frame(maxHeight: .infinity) // 让ScrollView占满屏幕可用高度
.background(Color("Body"))
.edgesIgnoringSafeArea(.bottom)
.navigationBarBackButtonHidden(true)

补充说明

  • contentAlignment(.center)是iOS14及以上支持的属性,能直接让容器内的内容在水平和垂直方向都居中,替代了原代码中多个Spacer的写法,布局更简洁。
  • 外层ScrollView设置maxHeight: .infinity后,会自动填充屏幕的可用高度,确保内部的ZStack和加载容器能真正占满空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:41:27