0

I'm trying to change the tab bar in my app programmatically with an animation.

In my tab bar delegate class, I currently have this, which I obtained from this thread.

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

    guard let fromView = selectedViewController?.view, let toView = viewController.view else {
        return false
    }

    UIView.transition(from: fromView, to: toView, duration: 0.3, options: [.transitionCrossDissolve], completion: nil)

    return true
}

The above animates tab bar changes when the user taps, but does not work for when the tab bar is changed programmatically, like in this case:

// code in another class
self.tabBarController?.selectedIndex = 2 // does not animate

I've read this thread that poses a similar question, but it's written in objective-c and from 4 years ago.

Is there any method that could animate programmatic tab bar changes?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Alan Dolan
  • 35
  • 1
  • 5

1 Answers1

2

As a workaround you could trigger your animation manually. I don't know if it is recommended but it is working for me.

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        animateTabBarChange(tabBarController: tabBarController, to: viewController)
        return true
    }

    func animateTabBarChange(tabBarController: UITabBarController, to viewController: UIViewController) {
        let fromView: UIView = tabBarController.selectedViewController!.view
        let toView: UIView = viewController.view

        // do whatever animation you like

    }

Then you call it like this:

let index = 2
animateTabBarChange(tabBarController: self.tabBarController!, to: self.tabBarController!.viewControllers![index])
self.tabBarController?.selectedIndex = index
Teetz
  • 3,475
  • 3
  • 21
  • 34