Swift 5在选项卡切换之前弹出所有控制器

时间:2019-04-22 08:47:39

标签: swift uitabbarcontroller tabbar

当我单击tabor项目时,我无法弹出所有控制器。我有以编程方式创建的Tabbar Controller。我想做的是...用户下一个方法:

extension TabbarViewController: UITabBarControllerDelegate{

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    self.navigationController?.popViewController(animated: false)
}

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
        self.navigationController?.popViewController(animated: false)
    })
}

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    self.navigationController?.popViewController(animated: false)
    return true
}
}

AppDelegate包含

 window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let rootNavController = UINavigationController(rootViewController: TabbarViewController())
    UIApplication.shared.keyWindow?.rootViewController = rootNavController

1 个答案:

答案 0 :(得分:0)

根据您的代码,选项卡栏控制器是导航控制器的根,因此self.navigationController将引用那个导航控制器。这意味着该行:

self.navigationController?.popViewController(animated: false)

将尝试从导航控制器中弹出选项卡栏控制器,但是由于它是根目录,因此它什么也不做。

我假设您具有导航控制器作为选项卡栏控制器的每个选项卡,并且您想将那些导航控制器弹出到其根目录,对吗?

您应该使用viewController参数来引用所需的导航控制器:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
        (viewController as? UINavigationController)?.popToRootViewController(animated: false)
    })
}