如何修改Navigation Controller返回按钮字体大小?能否全局设置?
解决导航栏返回按钮字体大小修改的问题
我之前也踩过这个坑!在viewWillAppear里修改经常不生效,主要是因为系统导航栏的返回按钮初始化时机和我们修改的时机不匹配,或者系统会覆盖自定义设置。下面分两个问题给你详细解答:
一、单个视图控制器修改返回按钮字体的正确方法
你有两种可靠的方式:
方法1:在跳转前的视图控制器中设置
返回按钮的样式其实是由跳转前的那个VC控制的(因为返回按钮属于上一个页面的导航项),所以你可以在准备push到目标VC的时候,自定义backBarButtonItem:
// 在当前VC的prepare(for:sender:)方法中 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let nextVC = segue.destination as? TargetViewController else { return } // 自定义返回按钮文本和字体 let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil) backBtn.setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) // 改成你要的字号 ], for: .normal) self.navigationItem.backBarButtonItem = backBtn }
这种方法的好处是不用处理返回逻辑,系统会自动帮你完成pop操作。
方法2:在当前VC中替换系统返回按钮
如果想在当前VC直接控制,你可以完全自定义左侧按钮,替换系统默认的返回按钮:
override func viewDidLoad() { super.viewDidLoad() // 创建自定义返回按钮 let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(handleBack)) backBtn.setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) ], for: .normal) // 替换系统返回按钮 self.navigationItem.leftBarButtonItem = backBtn } @objc private func handleBack() { self.navigationController?.popViewController(animated: true) }
为什么viewWillAppear里改没用?因为当viewWillAppear执行时,系统已经初始化好导航栏的返回按钮了,此时修改属性很容易被系统的默认设置覆盖。
二、全局统一设置所有VC的返回按钮字体
有两种全局方案,根据你的需求选择:
方案1:用UIAppearance全局配置
在AppDelegate的application(_:didFinishLaunchingWithOptions:)方法中设置UIBarButtonItem的全局外观,这样所有导航栏按钮(包括返回按钮)都会应用这个字体:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 设置正常状态下的字体 UIBarButtonItem.appearance().setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) ], for: .normal) // 可选:设置高亮/选中状态的字体 UIBarButtonItem.appearance().setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) ], for: .highlighted) return true }
⚠️ 注意:这个设置会影响所有UIBarButtonItem,如果你的导航栏右侧有其他按钮不需要这个字体,需要在对应VC里单独覆盖设置。
方案2:创建基类ViewController统一管理
如果你想更灵活地控制(比如部分VC不需要这个设置),可以创建一个基类BaseViewController,所有需要统一设置的VC都继承它:
class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 自定义返回按钮 let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(handleBack)) backBtn.setTitleTextAttributes([ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16) ], for: .normal) self.navigationItem.leftBarButtonItem = backBtn } @objc private func handleBack() { self.navigationController?.popViewController(animated: true) } }
之后你的其他VC只需要继承BaseViewController,就能自动应用这个返回按钮样式了。
内容的提问来源于stack exchange,提问作者WBuck
相关产品推荐
相关产品推荐

