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

如何在SwiftUI中创建位于Navigation bar下方的Toolbar?

在SwiftUI中实现导航栏下方的Toolbar

想要创建如图所示的、位于Navigation Bar下方的Toolbar:
导航栏下方的Toolbar示例

你当前的代码如下:

struct HomeView: View {
    var body: some View {

        NavigationView {
            ZStack {
                Color.yellow
            }
            .toolbar {
                ToolbarItem(placement: .navigation) {
                    Button {
                        
                    } label: {
                        Image(systemName: "globe")
                    }
                }
            }
        }
    }
}

实现方案

只需调整Toolbar的位置参数,即可在导航栏下方生成独立工具栏,修改后的代码示例:

struct HomeView: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.yellow
            }
            .toolbar {
                // 保留导航栏右侧按钮
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        // 按钮逻辑
                    } label: {
                        Image(systemName: "globe")
                    }
                }
                
                // 导航栏下方的工具栏
                ToolbarItemGroup(placement: .navigationBarBottom) {
                    Button {
                        // 左侧按钮逻辑
                    } label: {
                        Label("首页", systemImage: "house")
                    }
                    
                    Spacer()
                    
                    Button {
                        // 中间按钮逻辑
                    } label: {
                        Label("分类", systemImage: "square.grid.2x2")
                    }
                    
                    Spacer()
                    
                    Button {
                        // 右侧按钮逻辑
                    } label: {
                        Label("我的", systemImage: "person")
                    }
                }
            }
            .navigationTitle("主页") // 必须添加导航标题,否则导航栏无法正常渲染
        }
    }
}

关键说明

  • 使用ToolbarItemGroup(placement: .navigationBarBottom)指定导航栏下方的工具栏区域,可批量添加按钮、文本等控件
  • 单个控件也可直接用ToolbarItem(placement: .navigationBarBottom)定义
  • 必须设置navigationTitle,否则导航栏不显示,Toolbar位置会异常
  • 通过Spacer()可调整控件布局,实现分散或居中排列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:25:10