Simon Hessner
Simon Hessner

Reputation: 1837

Swift: Custom UINavigationController not called

I want to change the root controller of my navigation controller programatically:

import UIKit
import Foundation

class NavigationController : UINavigationController {
    override init(rootViewController : UIViewController) {
        print("TEST")
        super.init(rootViewController : rootViewController)
    }

    override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
        print("TEST2")
        super.init(navigationBarClass : navigationBarClass, toolbarClass : toolbarClass)
    }

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

I set the NavigationController class as custom class of my Navigation Controller in the storyboard

The console does not show my test output. What am I doing wrong and how can I change the root controller here?

Upvotes: 2

Views: 1664

Answers (2)

Simon Hessner
Simon Hessner

Reputation: 1837

Got it:

import UIKit
import Foundation

class NavigationController : UINavigationController {
    override init(rootViewController : UIViewController) {
        super.init(rootViewController : rootViewController)
    }

    override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
        super.init(navigationBarClass : navigationBarClass, toolbarClass : toolbarClass)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "new_main_view") as! ViewController
        self.setViewControllers([newViewController], animated: false)
    }
}

Is this the recommended way to provide the user two "themes" of the same view?

Upvotes: 0

Francesco Deliro
Francesco Deliro

Reputation: 3939

If you instantiate your custom NavigationController from Storyboard you are calling this method:

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

To see your print in console you have to init it programmatically, for example:

let navVC = NavigationController(rootViewController: yourVC)

Upvotes: 1

Related Questions