Sarah Boo Sarah Boo - 2 years ago 81
Swift Question

Correct location of navigation controller code for iOS?

For customizing the navigation bar in the navigator view, I used


to access it. I did this from the .swift file of the first view controller I had. It works fine but I was wondering if there is a better place to put the code that I am missing? Does anyone ever use separate .swift files for the navigation view?

Answer Source

That's not a horrible way to do it. It certainly gets the job done.

Depending on what you are trying to accomplish there are a couple ways you could access the navigation bar.

  1. For a situation where you need to customize the bar specifically for the view you are in, doing it the way you described is good.

One note: You are force-unwrapping navigationController. If you decide to do this you just need to make sure that view controller will always live inside a UINavigationController.

  1. In a situation where you want to customize the look and feel no matter what view you are in you could subclass a UINavigationController and in its viewDidLoad method do any sort of customization in there. Then instead of creating a navigation controller like this UINavigationController.init(rootViewController: someViewController), you would use your subclass of UINavigationController instead. YourNavigationControllerClass.init(rootViewController: someViewController)

For #2 you would want to create a new class and put the code in that new class viewDidLoad method.

enter image description here enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download