我们有Router类,将viewController导航到另一个视图控制器,它按预期工作,但是当viewControllersStack随机变为nil并发生崩溃时。我们尝试使用“ if let”来避免崩溃,但是问题是当viewControllersStack为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)
}
}
}
}