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

iOS全局自定义无文字导航返回按钮遇布局警告问题

解决自定义无文字返回按钮的布局警告问题

嘿,我懂你遇到的困扰了!你现在用的把返回按钮标题偏移-60来隐藏文字的方式,其实是个“取巧”的hack——系统并没有真正移除返回按钮的标题视图,只是把它挪到了屏幕外面,布局系统依然会计算这个视图的位置,自然就会抛出警告啦。

下面给你两种更规范的解决方案,既能实现无文字的自定义返回按钮,又能彻底消除布局警告:

方案一:iOS 14+ 专属(推荐)

从iOS 14开始,苹果提供了原生的方式定制返回按钮外观,我们可以通过UINavigationBarAppearance的backButtonAppearance直接处理标题:

let navBarAppearance = UINavigationBar.appearance()
navBarAppearance.backIndicatorImage = #imageLiteral(resourceName: "back")
navBarAppearance.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "back")

// 配置返回按钮外观,隐藏标题
let backButtonAppearance = UIBarButtonItemAppearance()
// 把标题文字设为透明,彻底隐藏
backButtonAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.clear]
backButtonAppearance.disabled.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.clear]
backButtonAppearance.highlighted.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.clear]

// 或者更直接:直接将标题设为空字符串
// backButtonAppearance.title = ""

navBarAppearance.backButtonAppearance = backButtonAppearance

这种方式是系统官方支持的,不会产生任何布局警告,还能全局生效。

方案二:兼容iOS 13及以下

如果你的App需要适配更低版本的iOS,可以用下面两种方式:

方式1:全局设置标题透明

let navBarAppearance = UINavigationBar.appearance()
navBarAppearance.backIndicatorImage = #imageLiteral(resourceName: "back")
navBarAppearance.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "back")

// 全局将返回按钮标题设为透明,同时取消极端偏移
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal)
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset.zero, for: .default)

方式2:通过视图控制器扩展统一设置空标题

写一个UIViewController的扩展,在每个控制器里设置返回按钮的空标题:

extension UIViewController {
    func setupEmptyBackButton() {
        // 设置空标题的返回按钮项,后续页面的返回按钮就不会显示标题了
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }
}

// 在每个视图控制器的viewDidLoad中调用
override func viewDidLoad() {
    super.viewDidLoad()
    setupEmptyBackButton()
}

这种方式需要在每个控制器里调用,但胜在兼容性好,完全不会有布局警告。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:35:45