首页 > 解决方案 > 如何以编程方式导航到 UIViewController?

问题描述

我在从另一个 UIViewController 以编程方式导航到 UIViewController 时遇到了困难。我正在使用 UIKit 和 Swift 5。

我试图关注这篇 Medium文章,但无法让它为我工作。

在我的 AppDelegate 文件中,我已将 didFinishLaunchingWithOptions 函数更改为:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = LoginViewController()
    self.window?.makeKeyAndVisible()

   return true
}

然后在我的 LoginViewController() 中,我尝试通过执行以下操作导航到我的 DashboardViewController:

 override func viewDidLoad() {
    super.viewDidLoad();

    // present a modal with an embed UINavigationController
    let rvc = DashboardViewController()
    let vc = UINavigationController(rootViewController: rvc)
    vc.modalPresentationStyle = .overFullScreen
    present(vc, animated: true, completion: nil)
}

但是 DashboardViewController 永远不会被调用。

我做错了什么,如何更改代码才能工作?

谢谢你。

标签: swiftswift5

解决方案


我最终看到了一个帮助我解决问题的 Youtube 视频。

应用委托

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let login = LoginViewController()
    let navigationController = UINavigationController(rootViewController: login)
    navigationController.setNavigationBarHidden(true, animated: true)

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()

    return true
}

登录视图控制器

let dashboard = DashboardViewController()
self.navigationController?.pushViewController(dashboard, animated: true)

推荐阅读