Swift – Instantiating a navigation controller without storyboards in App Delegate Swift – Instantiating a navigation controller without storyboards in App Delegate swift swift

Swift – Instantiating a navigation controller without storyboards in App Delegate


In Swift 3

Place this code inside didFinishLaunchingWithOptions method in AppDelegate class.

window = UIWindow(frame: UIScreen.main.bounds)let mainController = MainViewController() as UIViewControllerlet navigationController = UINavigationController(rootViewController: mainController)navigationController.navigationBar.isTranslucent = falseself.window?.rootViewController = navigationControllerself.window?.makeKeyAndVisible()


In AppDelegate

var window: UIWindow?var navController: UINavigationController?func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    navController = UINavigationController()    var viewController: ViewController = ViewController()    self.navController!.pushViewController(viewController, animated: false)    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)    self.window!.rootViewController = navController    self.window!.backgroundColor = UIColor.whiteColor()    self.window!.makeKeyAndVisible()    return true}

In ViewController

class ViewController: UIViewController {override func viewDidLoad() {    super.viewDidLoad()    self.title = "FirstVC"    var startFinishButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton    startFinishButton.frame = CGRectMake(100, 100, 100, 50)    startFinishButton.backgroundColor = UIColor.greenColor()    startFinishButton.setTitle("Test Button", forState: UIControlState.Normal)    startFinishButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)    self.view.addSubview(startFinishButton)}func buttonAction(sender:UIButton!){    println("Button tapped")    let vc = SecondViewController()    self.navigationController?.pushViewController(vc, animated: true)}override func didReceiveMemoryWarning() {    super.didReceiveMemoryWarning()    // Dispose of any resources that can be recreated.}}