How to add a navigation controller programmatically in code but not as initial view controller
You can add UINavigationController
like below :
First you have to create object of SecondViewController
,
let objVC: SecondViewController? = storyboard?.instantiateViewController(withIdentifier: "SecondViewController")
Or
let objVC: SecondViewController? = SecondViewController(nibName: "SecondViewController", bundle: nil)
Or
let objVC: SecondViewController? = SecondViewController()
Then add Navigation to SecondViewController
let aObjNavi = UINavigationController(rootViewController: objVC!)
If you want to present then use :
self.present(aObjNavi, animated: true) {
}
If you want to push then use :
self.navigationController?.pushViewController(aObjNavi, animated: true)
If you want to set as root controller then use :
let appDelegate: AppDelegate = (UIApplication.shared.delegate as? AppDelegate)!
appDelegate.window?.rootViewController = aObjNavi
var objVC: UIViewController? = storyboard.instantiateViewController(withIdentifier: "ViewController")
var aObjNavi = UINavigationController(rootViewController: objVC)
Now, instead of using view controller object use navigation controller object.