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

如何设置backBarButtonItem的边距?现有配置方法无效该怎么解决?

如何设置backBarButtonItem的边距

原代码不生效的核心原因

  • iOS 11之后系统导航栏使用自动布局渲染,原生backBarButtonItem的imageInsets、width属性会被系统默认布局规则覆盖,无法直接生效
  • backBarButtonItem属于当前页面的上一级父页面的navigationItem,如果在当前页面修改该属性,赋值对象错误也会导致修改不生效

可用解决方案

方案1:全局统一修改所有返回按钮边距

适合全App返回按钮边距统一的场景,使用系统外观代理实现:

// iOS 13及以上版本推荐使用UINavigationBarAppearance配置
if #available(iOS 13.0, *) {
    let navAppearance = UINavigationBar.appearance()
    // 调整返回按钮文字偏移量(horizontal为正就是向右偏移,负为向左偏移)
    navAppearance.backButtonAppearance.normal.titlePositionAdjustment = UIOffset(horizontal: 10, vertical: 0)
    // 调整返回图标边距
    navAppearance.backButtonAppearance.normal.backgroundImageInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
} else {
    // iOS 11~12版本用旧的外观API
    UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .default)
}

方案2:单个页面自定义返回按钮(灵活度最高)

如果只需要修改单个页面的返回按钮边距,直接自定义leftBarButtonItem替换系统默认返回按钮即可,不受系统布局限制:

// 1. 创建自定义返回按钮
let customBackBtn = UIButton(type: .system)
customBackBtn.setImage(UIImage(named: "back_icon"), for: .normal) // 也可以替换为系统返回图标
customBackBtn.setTitle("返回", for: .normal)
customBackBtn.titleLabel?.font = .systemFont(ofSize: 17)
customBackBtn.setTitleColor(.systemBlue, for: .normal)

// 2. 自定义边距
// 调整图标和文字的间距
customBackBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 5)
// 调整按钮整体的左右内边距
customBackBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 10)

// 3. 添加返回点击事件
customBackBtn.addTarget(self, action: #selector(popBack), for: .touchUpInside)

// 4. 替换系统默认返回按钮
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: customBackBtn)

// 5. 实现返回逻辑
@objc private func popBack() {
    navigationController?.popViewController(animated: true)
}

注意:自定义leftBarButtonItem后系统自带的侧滑返回手势会失效,需要补充下面的代码恢复:

// 仅需设置代理,不需要实现额外代理方法
navigationController?.interactivePopGestureRecognizer?.delegate = self

同时让当前页面遵循UIGestureRecognizerDelegate协议即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:30:05