[英]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.