How to add a navigation controller programmatically in code but not as initial view controller

*爱你&永不变心* 提交于 2019-11-30 03:41:51

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
Arpit Jain
var objVC: UIViewController? = storyboard.instantiateViewController(withIdentifier: "ViewController")

var aObjNavi = UINavigationController(rootViewController: objVC)

Now, instead of using view controller object use navigation controller object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!