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

SwiftUI 如何实现NavigationView居中显示logo、右侧放置按钮

解决方案

你之前的写法错误是因为没有使用正确的导航栏分区位置,iOS 14+ 可以通过Toolbar的不同placement参数直接实现需求,代码如下:

// 完整示例代码
NavigationView {
    // 你的页面主体内容
    Text("页面内容")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            // 居中logo放置在principal位置
            ToolbarItem(placement: .principal) {
                Image("mylogo")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 154, height: 42)
            }
            // 右侧按钮放置在navigationBarTrailing位置
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    // 按钮点击事件
                }) {
                    Image("hamburger_menu")
                        .resizable()
                        .frame(width: 24, height: 24)
                }
            }
        }
}

代码说明

  • placement: .principal 是导航栏的标题默认位置,放在这里的自定义视图会自动居中,完美替换文本标题
  • placement: .navigationBarTrailing 是导航栏右侧专属区域,元素会自动右对齐,不会和居中的logo产生布局冲突
  • 不需要额外设置空的navigationBarTitle,principal位置的内容会自动覆盖默认标题位
  • 如果logo尺寸过宽挤压右侧按钮,可给logo的frame增加maxWidth: UIScreen.main.bounds.width * 0.6参数,避免元素重叠

兼容iOS 13的方案

如果需要适配iOS 13,可以用overlay方式覆盖导航栏位置实现:

NavigationView {
    Text("页面内容")
        .navigationBarTitle("", displayMode: .inline)
        .navigationBarItems(trailing: Button(action: {}) {
            Image("hamburger_menu")
                .resizable()
                .frame(width: 24, height: 24)
        })
        .overlay(
            Image("mylogo")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 154, height: 42)
            , alignment: .top
        )
        .padding(.top, 8)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:24:02