How to Present a View Modally From UITabBarController in Swift

by

Each tab of a tab bar controller is associated with a view controller. When the user selects a specific tab, the tab bar controller displays the root view of the corresponding view controller, replacing any previous views. The tab bar interface displays tabs at the bottom for selecting between the different display views.

Tab bar controller lets us to implement easy multi-selection of displays easily. In this user interface style tabs at the bottom remains visible. Display switches between selection at child controller section above.

Comes a situation where view controller associated with a specific tab to display modally or push where Tabs at bottom gets covered behind this view controller. Instagram app is a good example where when create-post-tab is pressed, then display is opened over the tab controller.

How to present UITabBarItem’s view controller modally?



UITabBarControllerDelegate provides us set of methods to customize the behavior of a tab bar.

tabBarController(_:shouldSelect:)

Asks the delegate whether the specified view controller should be made active.


func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    //root controller of Tab Item here is UINavigationController in this example
    if let nav = viewController as? UINavigationController{
        if nav.viewControllers.first is MyViewController{
            //present MyViewController
            return false
        }
    }
    return true
}

We are intercepting the view controller that we want to present in our way. We have to return false to signal tab bar controller not to do anything. For rest of other tabs we will return true for default behaviour.

This can be applied to any other transitions. What I am trying to achieve is to break the child controller style display of tab bar controller.

You might also like: How to Send Local Video to iMessage in Swift

You might also like: How to Disconnect CoreBluetooth Peripheral cleanly in Swift

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts