首页 > 解决方案 > Swift - 在另一个标签栏项目上关闭视图控制器

问题描述

我有一个标签栏应用程序,每个标签都有一些显示segue。我希望能够从另一个选项卡栏中的操作中关闭一个选项卡栏中的视图控制器。

在我的示例中,当用户点击注销时,我想关闭每个选项卡中所有呈现的视图控制器。

标签栏控制器是根视图控制器:

let tabBarController = self.window!.rootViewController as? UITabBarController

我不确定我哪里出错了,因为我尝试过的以下许多代码片段对我不起作用......

    self.navigationController?.popToRootViewController(animated: true)

    self.view.window?.rootViewController?.dismiss(animated: false, completion: nil) //doesn't dismiss presented VC's on other tab bar controller

    UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)

self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)

dismissViewControllers()

dismiss(animated: false, completion: nil)

}

func dismissViewControllers() {

    guard let vc = self.presentingViewController else { return }

    while (vc.presentingViewController != nil) {
        vc.dismiss(animated: true, completion: nil)
    }
}

呈现的视图控制器仍在堆栈上。我在这里有什么明显的遗漏吗?

标签: swift

解决方案


为此,您需要实现的是如何在选择注销选项卡项时重置根视图控制器。要知道在 中选择了哪个项目,UITabBarController您需要检测何时按下选项卡栏项目


理论/伪代码:

通过组合以上几点,这是一个理论示例:

class SpecialTabBarController: UITabBarController, UITabBarControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if let _ = viewController as? LogoutViewController {
            // Reset root view controller of the UIWindow
            // And must call makeKeyAndVisible() on the UIWindow object
        }
    }
}

顺便说一句,如果从 Interface Builder 中使用,请不要忘记将其设置SpecialTabBarController为 Tab Bar Controller 的自定义类。


奖金:

这是一个完整的解决方案,您可以检查一下,尽管由于iOS 13 中引入的SceneDelegate 和 AppDelegate 之间SpecialTabBarController差异,需要考虑更多因素。


推荐阅读