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

导航栏右侧自定义Bar Button大小无法调整,求技术解决方案

解决自定义Bar Button尺寸不生效的问题

嘿,我之前也踩过这个坑!UIBarButtonItem对自定义视图的尺寸处理确实有它的“小脾气”,给你几个实用的排查思路和解决方向:

  • 先确认按钮的真实尺寸:给你的UIButton临时加个背景色,比如 button.backgroundColor = .systemPink,运行后看看按钮的实际显示范围是不是你设置的22x22。如果背景色显示的尺寸是对的,那问题大概率出在你的tune图片上——比如图片本身尺寸过小,或者没有开启拉伸模式。可以尝试设置图片的渲染模式:UIImage(named: "tune")?.withRenderingMode(.alwaysOriginal),或者检查图片的原始像素大小。

  • 用Auto Layout约束替代Frame:在导航栏的布局环境里,直接设置Frame经常会被系统的Auto Layout规则覆盖。换成约束来固定尺寸更可靠:

let button = UIButton(type: .custom)
button.setBackgroundImage(UIImage(named: "tune"), for: .normal)
button.addTarget(self, action: #selector(viewController.settingsBtnPressed), for: .touchUpInside)
// 添加固定宽高约束
button.widthAnchor.constraint(equalToConstant: 22).isActive = true
button.heightAnchor.constraint(equalToConstant: 22).isActive = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
  • 检查全局导航栏样式:看看你的项目里有没有在全局配置UIBarButtonItem的尺寸,比如在AppDelegate或者用UINavigationBar.appearance()设置了统一的按钮样式。这种全局设置会优先于你自定义视图的尺寸,暂时注释掉相关代码测试一下。

  • 直接用UIBarButtonItem的图片初始化方法:如果你的需求只是显示一张可点击的图片,完全不用绕弯子自定义UIButton,直接用系统的初始化方法更省心:

let settingsButton = UIBarButtonItem(
    image: UIImage(named: "tune"),
    style: .plain,
    target: self,
    action: #selector(viewController.settingsBtnPressed)
)
// 如果觉得图片大小不合适,还可以调整内边距
settingsButton.imageInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
self.navigationItem.rightBarButtonItem = settingsButton

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:49:32