Search code examples
swiftuinavigationcontrolleruitabbarcontroller

Best practice for presenting UITabBarControllers


I'm working on a project that has two different sets of tabs that are presented based on certain conditions. My question is how to best present the two different sets of tabs via their UITabBarControllers.

Right now, the app is meant to launch with the default UITabBarController but when I want to switch, I'm confused as to how to best present the second UITabBarController and completely get the first UITabBarController off the memory stack. And, vise versa. Would it be the same to switch back to the first UITabBarController?

This is the code used as of right now to switch from the first to the second.

let secondaryTabBarController = SecondaryTabBarController()
let secondaryTabs = UINavigationController(rootViewController: secondaryTabBarController)
UIApplication.shared.keyWindow?.rootViewController = secondaryTabs

Solution

  • To address your concern about memory, the method you suggested is completely fine in that regards and does not inherently cause any memory leaks.

    And yes, if you want to switch back to the first tab bar controller you can use the same method, creating a new instance of your first tab bar controller and setting it as the window's root view controller.

    You can animate the transition by using UIView.transition(with:duration:options:animations:completion:), which has some built-in transition animations.

    Alternatively you can use setViewControllers(viewControllers:animated:) on UITabBarController if you just want to change the tabs, or if you want to preserve selection.