I'm trying to detect which tab selected by the user, realtime. as an example, if user selecte 0 th
index, at the same time I want to get that user has selected the zeroth
index tab. so for that , I used tabbarcontroller
delegate method like below.
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
print("the selected index is : \(selectedIndex)")
}
but this shows the previous view controller.as an example think I'm in second tab
and then I select the first tab
then this prints the index as 2
.so how can I get the correct selected tab.
hope your help with this.
You can get index of selected UITabBarItem
by getting position of that particular item from array of items in UITabBar
. Try this out
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
print("the selected index is : \(tabBar.items.index(of: item))")
}
Swift 3.1:
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let items = tabBar.items else { return }
print("the selected index is : \(String(describing: items.index(of: item)))")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With