UITabBar(Controller) - Get index of tapped?

Viewed 34138

I've got a tab bar application and I need to know when and what button a user taps on the tab bar as to display the appropriate notifications and such.

In short: How would I go about detecting the index of a tapped UITabBarItem on a UITabBar?

Thanks in advance!

6 Answers

Simple extension for Swift 4:

extension UITabBarController {
    func getSelectedTabIndex() -> Int? {
        if let selectedItem = self.tabBar.selectedItem {
            return self.tabBar.items?.firstIndex(of: selectedItem)
        }
        return nil
    }
}

And usage:

let index = getSelectedTabIndex()
Related