Search code examples
iosswiftuiviewcontrollerviewcontrollerpushviewcontroller

Programmatically Pushing a ViewController


I'm trying to push a ViewController programmatically.

Code:

var plus = UIButton()

plus.addTarget(self, action: #selector(plusPressed), for: .touchUpInside)

@objc func plusPressed() {
    print("plus")
    let createJournalVC = CreateJournalViewController()
    self.navigationController?.pushViewController(createJournalVC, animated: true)
}

What works:

  1. Once the button is pressed, "plus" is printed to the console.

What doesn't work:

  1. The ViewController is not pushed.

Details

  • I am using a Navigation Controller & Tab Bar Controller.
  • I am making this only programmatic, no storyboards.
  • There is no error printed to the console, nothing actually happens.

Solution

  • If TabBarController comes after NavigationController then NavigationController can become nil. You should rather put TabBarController first and then put each ViewController (that are related to each tab) into there own NavigationController.

    Storyboard:

    Each Tab's ViewController gets their own NavigationController

    Programmatically:

    You need to create your TabBarController like this...

    window = UIWindow(frame: UIScreen.main.bounds)
    let tabCon = UITabBarController()
    let navCon1 = UINavigationController(rootViewController: ViewController())
    let navCon2 = UINavigationController(rootViewController: CreateJournalViewController())
    let navCon3 = UINavigationController(rootViewController: AnotherViewController())
    tabCon.viewControllers = [navCon1, navCon2, navCon3]
    tabCon.tabBar.items?[0].title = NSLocalizedString("VC", comment: "comment")
    tabCon.tabBar.items?[1].title = NSLocalizedString("CJV", comment: "comment")
    tabCon.tabBar.items?[2].title = NSLocalizedString("AVC", comment: "comment")
    window?.rootViewController = tabCon
    window?.makeKeyAndVisible()