Search code examples
iosswiftuinavigationcontrolleruitabbarcontroller

Present a Tab Bar View Modally when View Controller is embedded in a Navigation Controller?


My storyboard is arranged as so.

Red: Tab Bar Controller that segues to...
Orange: Nav Controllers that have embedded...
Green: View Controllers

storyboard arrangement

I want to make my Middle Tab View (green) present itself modally, sort of like how the reddit app does it with its middle 'Post to Reddit' button. When this Middle View is dismissed the original Tab that was open beforehand will be returned to. How can this be done?


Solution

  • One way to do this...

    Give the UINavigationController that is your 2nd tab a StoryboardID - such as "createItemsNavController" - then implement shouldSelect in your custom tab bar controller class.

    If the 2nd tab is selected (tabs, like all arrays, are Zero based), instantiate your "createItemsNavController" and present it, returning false for shouldSelect:

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
        guard let indexOfTab = viewControllers?.firstIndex(of: viewController) else {
            return true
        }
        
        if indexOfTab == 1 {
            if let vc = storyboard?.instantiateViewController(withIdentifier: "createItemsNavController") as? UINavigationController {
                present(vc, animated: true, completion: nil)
            }
            return false
        }
        
        return true
    
    }
    

    If you're going that route, you could also (and it might be a good idea to) replace that Tab connection in your Storyboard with a blank view controller... as you probably want to avoid having it loaded by the tab bar controller, even if you never allow that tab to be activated.

    As a side note: that could be a very confusing UX. Users (and Apple) like apps that conform to common interface actions. Since users are familiar with tab bars, where selecting a tab button switches to that tab, changing the functionality in this way may be frowned upon.

    Of course, it's your app, and your design choice...