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

如何通过代码设置导航栏左侧按钮尺寸?设置后标题偏移问题求解

导航栏左侧自定义按钮尺寸异常导致标题偏移的问题解析

你遇到的这个问题,不完全是图片尺寸的锅,核心原因是UIBarButtonItem对自定义视图的布局规则在起作用——当你用customView初始化UIBarButtonItem时,系统并不会直接沿用你给UIButton设置的frame,而是会根据导航栏的默认布局约束自动调整视图大小,再加上自定义视图的内边距、内容适配等因素,最终挤压了标题的位置,导致偏移。

下面给你几个靠谱的解决方案,你可以根据需求选择:


方法一:给自定义按钮添加明确的Auto Layout约束

直接设置frame在Auto Layout环境下很容易被系统覆盖,不如给按钮添加固定尺寸的约束,同时调整内边距确保图片显示正常:

let backButton = UIButton(type: .custom)
backButton.setBackgroundImage(UIImage(named: "hipster_pelo2.png"), for: .normal)
// 强制设置按钮的宽高
backButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
// 调整内边距,避免图片被不必要的拉伸或留白
backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

方法二:直接用UIBarButtonItem的image属性设置(更简洁)

如果你的图片本身尺寸合适,完全可以不用自定义按钮,直接用系统提供的方式设置,系统会自动适配导航栏的布局:

// 注意设置withRenderingMode,避免系统默认色调覆盖图片原有颜色
let backImage = UIImage(named: "hipster_pelo2.png")?.withRenderingMode(.alwaysOriginal)
let backButton = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(backAction))
self.navigationItem.leftBarButtonItem = backButton

// 记得实现对应的点击方法
@objc func backAction() {
    navigationController?.popViewController(animated: true)
}

方法三:手动校准导航栏标题的位置

如果前两种方法还是存在标题偏移的情况,可以通过自定义titleView来强制控制标题的居中位置:

// 先检查是否已有自定义titleView,没有的话创建一个UILabel
if let titleView = navigationItem.titleView as? UILabel {
    titleView.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
} else {
    let titleLabel = UILabel()
    titleLabel.text = title
    titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
    titleLabel.textColor = .black
    navigationItem.titleView = titleLabel
    titleLabel.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
}

另外关于图片尺寸的小建议:最好准备适配不同分辨率的资源(@2x、@3x版本),比如你想要30x30pt的按钮,对应的@2x图片是60x60px,@3x是90x90px,这样能保证在不同设备上显示清晰,也能减少系统对图片的拉伸压缩,间接避免布局异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:45:53