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

如何修改UINavigationController控制的UINavigationBar首尾边距?

调整UINavigationBar按钮的Leading/Trailing边距方案

当然可以!针对你想给返回按钮和完成按钮留出更多空间的需求,我整理了几个实用的方法,适配不同的场景:

1. 单独控制单个Bar Button Item的内边距

这是最直接的方式,如果你只需要调整某几个特定按钮的边距,直接给对应的UIBarButtonItem设置contentEdgeInsets就行:

// 自定义返回按钮,左侧增加16pt空间
let backBtn = UIBarButtonItem(image: UIImage(systemName: "arrow.left"), 
                              style: .plain, 
                              target: self, 
                              action: #selector(goBack))
backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)

// 自定义完成按钮,右侧增加16pt空间
let doneBtn = UIBarButtonItem(title: "完成", 
                              style: .done, 
                              target: self, 
                              action: #selector(completeAction))
doneBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 16)

// 赋值给导航栏
navigationItem.leftBarButtonItem = backBtn
navigationItem.rightBarButtonItem = doneBtn

这个方法的优势是精准控制,不会影响其他导航栏元素。

2. 全局统一调整(iOS13+推荐)

如果你希望所有页面的导航栏按钮都统一边距,用UINavigationBarAppearance是Apple推荐的方式,一次配置全局生效:

let navBarAppearance = UINavigationBarAppearance()

// 给普通按钮设置左侧内边距
navBarAppearance.buttonAppearance.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
// 给"done"样式的按钮单独设置右侧内边距
navBarAppearance.doneButtonAppearance.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 16)

// 应用到导航栏
navigationController?.navigationBar.standardAppearance = navBarAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance // 适配滚动到顶部的样式

3. 用CustomView实现更灵活的布局

如果上面的方法满足不了你的复杂需求(比如按钮需要特殊尺寸或额外的装饰),可以把按钮包装在一个UIView里,再作为UIBarButtonItem的customView:

// 创建返回按钮的容器View
let backContainer = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
let backBtn = UIButton(type: .system)
backBtn.setImage(UIImage(systemName: "arrow.left"), for: .normal)
backBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside)
// 让按钮在容器里靠左偏移16pt
backBtn.frame = CGRect(x: 16, y: 0, width: 44, height: 44)
backContainer.addSubview(backBtn)

// 转成BarButtonItem
let backBarItem = UIBarButtonItem(customView: backContainer)
navigationItem.leftBarButtonItem = backBarItem

小提示

如果想修改系统默认的返回按钮边距,建议先隐藏系统返回按钮(navigationItem.hidesBackButton = true),再自己创建自定义返回按钮,这样能完全控制样式和边距,避免系统默认样式的干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:13:30