【问题标题】:Resetting the navigation stack on a UITabBarController doesn't work在 UITabBarController 上重置导航堆栈不起作用
【发布时间】:2019-12-25 07:33:54
【问题描述】:

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

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

UINavigationController => ControllerA(UIViewController 的子类)=> ControllerB (UIViewController 的子类) => ControllerC (a 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 的子类)中不起作用,因为 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)
  }
}

这可行,但 ControllerB 在显示 ControllerA 之前短暂可见。

任何帮助将不胜感激!

【问题讨论】:

  • ControllerCUITabBarController 的子类吗?还是您的UITabBarController 中的第一个视图控制器
  • 是的,它是 UITabBarController 的子类。感谢您的评论,我已经编辑了问题

标签: ios swift uiviewcontroller uitabbarcontroller


【解决方案1】:

在 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 之前短暂可见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多