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

Swift navigation bar标题图片偏移:添加右侧按钮后如何居中?

解决导航栏添加右侧按钮后标题图片左偏的问题

这个问题我做项目时也踩过坑!导航栏的标题视图默认会被左右BarButtonItem的布局影响——当你添加右侧按钮后,系统会自动调整标题位置给按钮腾空间,导致图片标题偏移。下面几个实用方法能帮你让标题图片稳稳居中:


方法1:用容器视图包裹图片,强制居中约束

这是最稳妥的方案,通过独立容器视图隔绝左右按钮的布局干扰,让图片始终在容器中央,而容器作为titleView会保持导航栏的居中位置:

// 创建标题图片视图
let titleImage = UIImage(named: "your-title-image")
let titleImageView = UIImageView(image: titleImage)
titleImageView.contentMode = .scaleAspectFit // 适配图片显示

// 创建容器视图,作为导航栏的titleView载体
let titleContainer = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 44))
titleImageView.translatesAutoresizingMaskIntoConstraints = false
titleContainer.addSubview(titleImageView)

// 给图片添加居中约束
NSLayoutConstraint.activate([
    titleImageView.centerXAnchor.constraint(equalTo: titleContainer.centerXAnchor),
    titleImageView.centerYAnchor.constraint(equalTo: titleContainer.centerYAnchor),
    titleImageView.widthAnchor.constraint(equalToConstant: 120), // 根据你的图片尺寸调整
    titleImageView.heightAnchor.constraint(equalToConstant: 35)
])

// 设置导航栏标题视图
navigationItem.titleView = titleContainer

方法2:添加左侧占位按钮,平衡左右宽度

如果你的右侧按钮宽度固定,可以给左侧加一个宽度相同的占位BarButtonItem,让系统认为左右布局对称,自然会把标题放在中间:

// 创建右侧功能按钮
let rightActionButton = UIBarButtonItem(title: "操作", style: .plain, target: self, action: #selector(rightButtonTapped))

// 创建左侧占位按钮,宽度和右侧按钮一致
let leftSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
leftSpacer.width = 60 // 可以直接设为右侧按钮的宽度,或者根据需求调整

// 给导航栏设置按钮
navigationItem.rightBarButtonItem = rightActionButton
navigationItem.leftBarButtonItems = [leftSpacer]

方法3:直接绑定titleView到导航栏中心锚点

通过Auto Layout直接让titleView和导航栏的中心对齐,不过要注意在布局完成后再设置约束,避免冲突:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    guard let titleView = navigationItem.titleView, let navBar = navigationController?.navigationBar else { return }
    // 强制titleView和导航栏中心对齐
    titleView.centerXAnchor.constraint(equalTo: navBar.centerXAnchor).isActive = true
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:57:56