以编程方式推送 ViewController

Programmatically Pushing a ViewController

我正在尝试以编程方式推送 ViewController。

代码:

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)
}

什么有效:

  1. 按下按钮后,"plus" 会打印到控制台。

什么不起作用:

  1. ViewController没有推送。

详情

如果 TabBarController 在 NavigationController 之后,那么 NavigationController 可以变为 nil。您应该首先放置 TabBarController,然后将每个 ViewController(与每个选项卡相关)放入自己的 NavigationController。

故事板:

以编程方式:

您需要像这样创建 TabBarController...

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()

似乎navigationControllernil,这就是视图控制器没有被推送的原因。