Setting UINavigationController's navigation bar and rootViewController in the same time
Asked Answered
B

2

5

I am facing a dilemma trying to set a UINavigationController's rootView UIViewController and UINavigationBar in the same time. It seems that a UINavigationController can be either initiated with a rootViewController as so:

let navController = UINavigationController(rootViewController: someViewController)

or with a UINavigatioBar, like so:

let navController = UINavigationController(navigationBarClass: someUINavigationBar, toolbarClass: nil)

However, I would like to be able to add a rootViewController as well as a custom UINavigationBar. Is there any way to do so?

I've tried setting the UINavigationBar like navController.navigationController?.navigationBar = MyNavigationBar however, it seems that navigationController?.navigationBar is only a getter.

Bab answered 22/1, 2018 at 20:14 Comment(0)
C
9

The rootViewController is just the first view controller to be displayed. While it seems to be inaccessible from nowhere you can just set the viewControllers stack property to one view controller, your root.
Here is an extension with a convenience initializer.

extension UINavigationController {

    convenience init(navigationBarClass: Swift.AnyClass?, toolbarClass: Swift.AnyClass?, rootViewController: UIViewController) {
        self.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
        self.viewControllers = [rootViewController]
    }

}
Cohl answered 22/1, 2018 at 20:26 Comment(0)
S
2

Why don't you just set the rootViewController after creating the navController?

let navController = UINavigationController(navigationBarClass: someUINavigationBar, toolbarClass: nil)
navController.viewControllers = [someRootViewController]
Skilful answered 22/1, 2018 at 20:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.