Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 759
dre_84w934 Avatar asked Jan 02 '23 22:01

dre_84w934


2 Answers

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

}
like image 106
Andrea Avatar answered Jan 05 '23 14:01

Andrea


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

let navController = UINavigationController(navigationBarClass: someUINavigationBar, toolbarClass: nil)
navController.viewControllers = [someRootViewController]
like image 24
Milan Nosáľ Avatar answered Jan 05 '23 16:01

Milan Nosáľ