Search code examples
iosswiftuitabbarcontroller

shouldSelect method of UITabBarControllerDelegate never invoked


I am using Swift 4 and XCode 9. I am trying to programmatically control navigation in my UITabBarController. According to Apple's documentation, I need to implement the UITabBarControllerDelegate protocol. However, the method I implemented never get called:

import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        tabBarController?.delegate = self
    }

    func tabBarController(_ tabBarController: UITabBarController,
            shouldSelect viewController: UIViewController) -> Bool {
        print("Should go here...")
        return true
    }
}

Any idea what I am doing wrong?


Solution

  • Your problem is that you are setting the wrong delegate. Update viewDidLoad to:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.delegate = self // or just "delegate = self"
    }
    

    The idea is that you want this tab controller to be its own delegate.