NEW: Master Swift design patterns with my latest book! >>

How do you show a modal view controller when a UITabBarController tab is tapped?

Written by Paul Hudson    @twostraws

Usually tapping a tab in a UITabBar shows that tab, but it's often the case that you want to override that behavior, for example to show a view modally. If you're using one of Xcode's built-in storyboard templates for creating your user interface, it's not immediately obvious how to do this, but fortunately it's not so hard using the approach below.

First, find the viewDidLoad() method for your initial view controller – whichever one is shown first in your app. Now add this code to it:

self.tabBarController?.delegate = UIApplication.shared.delegate as? UITabBarControllerDelegate

That sets up your application delegate (in AppDelegate.swift) to handle events from the tab bar controller. This line uses optionals safely, so it will do nothing if you change your app structure later.

Now open AppDelegate.swift, and add UITabBarControllerDelegate to the list of protocols your app delegate conforms to, like this:

class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {

Finally, you should implement the shouldSelect method on your app delegate, which must return true or false depending on whether you want the regular tab behavior (return true) or your own (return false).

In the example below, I want the regular view controller behavior for all tabs unless the user is trying to show one with the class YourViewController. When that happens, I'll create a new view controller and show it modally instead:

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if viewController is YourViewController {
        if let newVC = tabBarController.storyboard?.instantiateViewController(withIdentifier: "YourVCStoryboardIdentifier") {
            tabBarController.present(newVC, animated: true)
            return false

    return true

There are two things to note about that code. First, you'll need to give your view controller a storyboard identifier so that instantiateViewController(withIdentifier:) will work. Second, this won't have any extra performance impact on your code – the view that would have been shown wasn't created yet, so creating a new one here won't be duplicating any work.

Available from iOS 7.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

Click here to visit the Hacking with Swift store >>