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

SwiftUI TabView高度异常 子视图无法垂直居中问题求助

SwiftUI TabView 与 Toolbar 适配导致布局偏移问题

在实现SwiftUI的TabView时遇到布局异常,不确定是使用方式错误还是SwiftUI本身的问题。

复现代码

App 入口代码

import SwiftUI

@main
struct MyPlaygroundAppApp: App {
    init() {
        let toolbarAppearance = UIToolbarAppearance()
        toolbarAppearance.backgroundColor = UIColor(Color.green)
        
        UIToolbar.appearance().standardAppearance = toolbarAppearance
        UIToolbar.appearance().scrollEdgeAppearance = toolbarAppearance
        UIToolbar.appearance().compactAppearance = toolbarAppearance
        UIToolbar.appearance().compactScrollEdgeAppearance = toolbarAppearance
    }
    
    var body: some Scene {
        WindowGroup {
            PlayContentView()
        }
    }
}

视图代码

import SwiftUI

struct PlayContentView: View {
    var body: some View {
        TabView {
            ContentView()
        }
        .background(Color.green)
        .edgesIgnoringSafeArea(.top)
        .tabViewStyle(.page(indexDisplayMode: .never))
    }
}

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                VStack(spacing: 0) {
                    ZStack {
                        VStack(spacing: 0) {
                            Text("Title")
                            Text("Text")
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: 80, alignment: .bottom)
                    .padding(.top, 12)
                    .background(Color.yellow)
                    Divider()
                        .overlay(Color.black)
                }
                
                ScrollView([.vertical, .horizontal], showsIndicators: false) {
                    VStack {
                    }
                    .frame(width: 200, height: 300)
                    .frame(maxWidth: .infinity)
                    .background(Color.gray)
                }
                .background(Color.blue)
            }
            .toolbar {
                ToolbarItem(placement: .status) {
                    Text("press me")
                }
            }
        }
    }
}

#Preview {
    PlayContentView()
}

异常现象与测试结果

  • 运行后,ScrollView内的灰色容器无法垂直居中,顶部空间明显大于底部
  • 将TabView替换为ZStack后,布局恢复正常
  • 设置tabViewStyle(.page(indexDisplayMode: .always))时,底部出现页码指示器栏,灰色容器恢复居中
  • 移除Toolbar后,ScrollView的蓝色背景延伸至屏幕底部,灰色容器也能正常居中

怀疑是TabView未正确计算Toolbar的高度,导致布局偏移。请问是否有其他开发者遇到过该问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 03:20:00