swift 导航控制器 return 尝试导航到另一个视图控制器时为零

swift navigation controller return nil when trying to navigate to another View Controller

我们有路由器 class 将 viewController 导航到另一个视图控制器,它按预期工作,但随机 viewControllersStack 变为 nil 并发生崩溃。我们尝试使用它 "if let" 来避免崩溃,但这里的问题是当 viewControllersStack 为 nil 时出现黑屏。所以我们把它还原了。如果navigation为nil,请问为什么navigation stack为nil,如何处理?

private func PopOrPushToViewController(_ strControllerClass: String) {

    //get the list of controllers in the stack
    let viewControllersStack: [UIViewController] = self.navigationController!.viewControllers as [UIViewController]
    var boolDidNaviagtion = false
    for viewController in viewControllersStack {
        if boolDidNaviagtion {
            viewController.removeFromParent()
        }
        if String(describing: type(of: viewController)) == strControllerClass {
            boolDidNaviagtion = true
            self.navigationController?.popToViewController(viewController, animated: true)
        }
    }
    if !boolDidNaviagtion {
        let viewController = NavigationController.sharedInstance.storyboardViewControllerFromString(strControllerClass)!
        self.navigationController!.pushViewController(viewController, animated: true)
    }
}



class AddTripViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func navigate(_ sender: Any) {
        popOrPushToViewController( "ListViewController")
    }

}

问题可能出在您使用:

viewController.removeFromParent()

如果您 pop 到堆栈中的一个 VC,其他 VC 将被自动删除。

尝试将您的函数更改为:

private func PopOrPushToViewController(_ strControllerClass: String) {

    // get the list of controllers in the stack
    if let vcStack: [UIViewController] = self.navigationController?.viewControllers {

        var didPop = false

        for vc in vcStack {

            // if we find the desired VC already in the navVC's stack of controllers,
            // pop to it, set the didPop flag to true, and quit looking
            if String(describing: type(of: vc)) == strControllerClass {
                self.navigationController?.popToViewController(vc, animated: true)
                didPop = true
                break
            }

        }

        // if we did NOT pop to the desired VC,
        // instantiate it and push it onto the stack
        if !didPop {
            if let vc = NavigationController.sharedInstance.storyboardViewControllerFromString(strControllerClass) {
                navigationController?.pushViewController(vc, animated: true)
            }
        }

    }

}