【问题标题】:Swift - dismiss a view controller on another tab bar itemSwift - 在另一个标签栏项目上关闭视图控制器
【发布时间】:2020-04-15 04:40:11
【问题描述】:

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

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

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

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

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

    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


    【解决方案1】:

    在选择注销选项卡项时,您需要How to reset root view controller。要知道在UITabBarController 中选择了哪个项目,您需要Detect when a tab bar item is pressed


    理论/伪代码:

    综合以上几点,这是一个理论上的例子:

    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 设置为标签栏控制器的自定义类。


    奖金:

    Here is a complete solution,您可以检查一下,尽管由于 iOS 13 中引入了Difference between SceneDelegate and AppDelegateSpecialTabBarController 中有更多考虑因素。

    【讨论】:

    • 非常感谢!在注销时重新实例化根视图控制器对我来说效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多