Search code examples
iosswiftuinavigationcontroller

Customize Back Button for all Appearances in the App


I want to change the appearance of all Back buttons in the app by setting the text to "Back" and removing the arrow (even just removing the arrow would be fine). I'm trying to find a way to do it globally for all view controllers in the app while also keeping the functionality (I don't want to create a new instance of a UIBarButtonItem and having to set the selector).

I created a custom UINavigationController and tried to set the back button title there with navigationItem.backBarButtonItem?.title = "Back", but it didn't work. Any suggestions how to do it properly?


Solution

  • Just create CustomNavigationController then at override open func pushViewController(_ viewController: UIViewController, animated: Bool) do controlClearBackTitle method

    then use CustomNavigationController to fix it all in your app

    enter image description here

    import UIKit
    
    class CustomNavigationController: UINavigationController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        override open func pushViewController(_ viewController: UIViewController, animated: Bool) {
            controlClearBackTitle()
            super.pushViewController(viewController, animated: animated)
        }
    
        override open func show(_ vc: UIViewController, sender: Any?) {
            controlClearBackTitle()
            super.show(vc, sender: sender)
        }
    
        func controlClearBackTitle() {
    
            self.navigationBar.backIndicatorImage = UIImage()
            self.navigationBar.backIndicatorTransitionMaskImage = UIImage()
            topViewController?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "AnyTitle", style: .plain, target: nil, action: nil)
    
        }
    }