UINavigationController 不会推送 ViewController

UINavigationController won't pushViewController

我有两个 ViewController。一个叫 LoginVC,也是我的 rootviewcontroller,另一个叫 SignUpVC。

在我的 AppDelegate 中,我将 UINavigationbar 设置如下:

var window: UIWindow?

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

    window = UIWindow()
    window?.rootViewController = UINavigationController(rootViewController: LoginVC())

    return true
}

然后在我的 LoginVC 中,我使用它来显示我的 SignUpVC,但它不起作用。

@objc func handleShowSignUp() {
    let signUpVC = SignUpVC()
    navigationController?.pushViewController(signUpVC, animated: true)
}

有人可以向我解释我做错了什么吗?

您应该以这种方式使用 File SceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow? // create Window

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let LoginVC = ViewController() //create your viewController
        nav.pushViewController(contentView, animated: true) 
               if let windowScene = scene as? UIWindowScene {
                   let window = UIWindow(windowScene: windowScene)
                   window.rootViewController = LoginVC
                   SceneDelegate.window = window
                   window.makeKeyAndVisible()
               }
    }

重要提示:您可以查看 UIWindowScene

直接初始化 LoginVC() 和 SignUpVC() 有点不对。如果您使用的是故事板,请尝试这样的事情

let storyboard = UIStoryboard.init(name: "YOUR_STORYBOARD_NAME", bundle: nil)
let nav = storyboard.instantiateInitialViewController() //if you want the initial one

let storyBoard: UIStoryboard = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil)
let someVC: SomeViewController = giftStoryBoard.instantiateViewController(withIdentifier: "SomeViewController") as! SomeViewController //don't forget to set identifier on interfacebuilder

如果您只使用 .xib

let myViewController = MyViewController(nibName: "MyViewController", bundle: nil)

然后尝试将其推送到导航控制器

这在 SceneDelegate 文件中起到了作用:

    @available(iOS 13.0, *)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    guard let scene = scene as? UIWindowScene else { return }
    window = UIWindow(windowScene: scene)
    window?.rootViewController = UINavigationController(rootViewController: LoginVC())
    window?.makeKeyAndVisible()
}