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

如何同时实现TabView(.page)动画滑动与透明工具栏?

解决TabView.page样式下透明工具栏的问题

要同时保留TabView的.page滑动切换动画和透明底部工具栏,可以通过调整工具栏背景设置来实现,具体代码修改如下:

修改后的完整代码

struct TestView: View {
    
    @State private var tabSelection = 1

    var body: some View {
        TabView(selection: $tabSelection) {
            Tab_HomeView(tabSelection: $tabSelection).tag(1)
            Tab_UserView(tabSelection: $tabSelection).tag(2)
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
        .toolbar {
            ToolbarItem(placement: .bottomBar) {
                HStack(spacing: 40) {
                    Button(action: { tabSelection = 1 } ) { 
                        Image(systemName: "house.fill")
                            .foregroundColor(.white)
                    }
                    Button(action: { tabSelection = 2 } ) { 
                        Image(systemName: "person.badge.key")
                            .foregroundColor(.white)
                    }
                }
            }
        }
        // 设置底部工具栏背景透明
        .toolbarBackground(.transparent, for: .bottomBar)
        // 隐藏系统默认的工具栏背景
        .toolbarBackground(.hidden, for: .bottomBar)
        // 让页面内容延伸到屏幕底部,配合透明工具栏效果
        .ignoresSafeArea(edges: .bottom)
    }
}

struct Tab_HomeView: View {
    
    @Binding var tabSelection: Int
    
    var body: some View {
        ZStack {
            Color.red
            Text("1")
                .foregroundColor(.white)
        }
        .ignoresSafeArea()
    }
}

struct Tab_UserView: View {
    
    @Binding var tabSelection: Int
    
    var body: some View {
        ZStack {
            Color.green
            Text("2")
                .foregroundColor(.white)
        }
        .ignoresSafeArea()
    }
}

关键调整说明

  • .toolbarBackground(.transparent, for: .bottomBar):明确指定底部工具栏的背景为透明状态
  • .toolbarBackground(.hidden, for: .bottomBar):强制移除系统默认添加的纯色工具栏背景
  • .ignoresSafeArea(edges: .bottom):让TabView的页面内容延伸到屏幕底部,使透明工具栏直接叠加在页面内容上,还原你最初默认TabView的视觉效果
  • 给按钮设置白色前景色:适配深色页面背景,确保按钮图标清晰可读

这样修改后,既可以保留TabView.page的滑动切换动画,又能实现底部工具栏的透明效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:25:21