【发布时间】: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 之前短暂可见。
任何帮助将不胜感激!
【问题讨论】:
-
ControllerC是UITabBarController的子类吗?还是您的UITabBarController中的第一个视图控制器? -
是的,它是 UITabBarController 的子类。感谢您的评论,我已经编辑了问题
标签: ios swift uiviewcontroller uitabbarcontroller