Andrej Andrej - 4 months ago 22
Swift Question

Can't change tab inside tabBar(tabBar: didSelectItem item:)

I'd like to toggle the selected tab when the user taps on tab. Let say if I have two tabs and the first is displayed, then tapping on first tab (as well as tapping on the second tab) should lead me to the second tab. I've implemented a custom UITabBarController as seen below.

class CustomizedTabBarContorller: UITabBarController {

override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.selectedIndex = 1 // this way works
}


override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

if tabBar.items?.indexOf(item) == self.selectedIndex {
self.selectedIndex = (selectedIndex == 0) ? 1 : 0 // doesn't work
}
}

}


How to change the tab, based on the selected and tapped tab?

I've also looked at:

UITabBar can't change selected index

UITabBarController Set a Default Tab

...and many others.

Answer

Moving self.selectedIndex = self.selectedIndex == 0 ? 1 : 0 to main queue solves the issue. Works like a charm.

if tabBar.items?.indexOf(item) == self.selectedIndex {
    dispatch_async(dispatch_get_main_queue(), { 
        self.selectedIndex = self.selectedIndex == 0 ? 1 : 0
    } 
}