1

I have a subclass of UINavigationBar and I want to make a subclass of UINavigationController that uses this UINavigationBar subclass. I know how to set the default UINavigationController to use a custom Navigation Bar

let navController = UINavigationController(navigationBarClass: CustomNavigationBar.self, toolbarClass: nil)

however I want to be able to create a custom UINavigationController (programatically) that already sets my custom navigation bar as its navigation bar class. I have seen how to do it at this link but it seems a bit dated (2012) and 'hacky AF' - https://stackoverflow.com/a/9610801/2654425. I know how to do it in 'Storyboard' by setting the navigation bar class of the UINavigationController but I would like this to be done programmatically in my Custom UINavigation Controller.

Here is a basic UINavigationBar and UINavigationController Subclass:

class CustomNavigationBar: UINavigationBar {

    override init(frame: CGRect) {
        super.init(frame: frame)

    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!


    }

    override func draw(_ rect: CGRect) {
        self.backgroundColor = UIColor.red
    }


}

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.
    }


}

Im not sure where to set the custom navigation bar. Any help is greatly appreciated. :)

Community
  • 1
  • 1
DevC
  • 6,982
  • 9
  • 45
  • 80

1 Answers1

1

You should set when you instantiate your UINavigationController subclass. Specifically, UINavigationController.init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?). See UINavigationController in Apple's documentation.

Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172