繁体   English   中英

重置UITabBarController上的导航堆栈不起作用

[英]Resetting the navigation stack on a UITabBarController doesn't work

我正在尝试在UINavigationController嵌入的UITabViewController的子类上重置导航堆栈,但是它不起作用。

我以编程方式创建的导航堆栈是这样的:

UINavigationController => ControllerA(UIViewController的子类)=> ControllerB(UIViewController的子类)=> ControllerC(UITabBarController的子类)。

当用户按下“后退”按钮或从ControllerC向后滑动时,该应用应返回到ControllerA,而不是ControllerB。

通常,当我想重置导航堆栈时,可以在Controller的viewDidLoad()方法中进行此操作:

override func viewDidLoad() {

  super.viewDidLoad()

  // usually work, but not in a subclass of UITabBarController as self.navigationController is nil
  if let navigationController = self.navigationController {

    // keep only the root controller (0) and the current controller
    navigationController.viewControllers = [navigationController.viewControllers[0], self]
  }
}

但这在ControllerC( UITabViewController的子类)中UITabViewController因为self.navigationController为nil。

如果我改为这样做(仍然在ControllerC的viewDidLoad()方法中):

/// ControllerC's viewDidLoad
override func viewDidLoad() {

  super.viewDidLoad()

  if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {

    // keep only the root controller (0) and the current controller
    navigationController.viewControllers = [navigationController.viewControllers[0], self]
  }
}

这可行,但是当我这样做时,ControllerB和ControllerC之间没有动画:

controllerB.navigationController?.pushViewController(ControllerC(), animated: true)

我还尝试覆盖ControllerC的viewWillDisappear()方法:

/// ControllerC's viewWillDisappear
override func viewWillDisappear(_ animated: Bool) {

  super.viewWillDisappear(animated)

  if self.isMovingFromParent {

    if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {

     navigationController.popToRootViewController(animated: true)
  }
}

这可以工作,但是在显示ControllerA之前短暂可见ControllerB。

任何帮助将不胜感激!

在ControllerC中,您可以像这样重写viewDidAppear()而不是尝试重写viewWillDisappear()方法:

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        if let navC = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
            // keep only the root controller (0) and the current controller
            navC.viewControllers = [navC.viewControllers[0], self]
        }
    }

当您向后浏览时,ControllerB在ControllerA之前不会短暂可见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM