title: How can I switch tabs in Tab Bar Controller so that the delegate method is informed of the user switching tabs?
body: <p>I've tried <code>selectedIndex</code> and <code>selectedViewController</code> but they do not call the delegate that adds an animation.</p>
  
  <p><a href="https://i.stack.imgur.com/7Fxr3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Fxr3.png" alt="Storyboard"></a></p>
  
  <p>The tab bar delegate:</p>
  
  <pre><code>class TabBarViewController: UITabBarController, UITabBarControllerDelegate {
  
  override func viewDidLoad() {
      super.viewDidLoad()
      self.delegate = self
  }
  
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
  }
  func animateToTab(toIndex: Int) {
      let tabViewControllers = viewControllers!
      let fromView = selectedViewController!.view
      let toView = tabViewControllers[toIndex].view
      let fromIndex = tabViewControllers.index(of: selectedViewController!)
  
      guard fromIndex != toIndex else {return}
  
      fromView?.superview!.addSubview(toView!)
  
      let screenWidth = UIScreen.main.bounds.size.width;
      let scrollRight = toIndex &gt; fromIndex!;
      let offset = (scrollRight ? screenWidth : -screenWidth)
      toView?.center = CGPoint(x: (fromView?.center.x)! + offset, y: (toView?.center.y)!)
  
      view.isUserInteractionEnabled = false
  
      UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
  
          fromView?.center = CGPoint(x: (fromView?.center.x)! - offset, y: (fromView?.center.y)!);
          toView?.center   = CGPoint(x: (toView?.center.x)! - offset, y: (toView?.center.y)!);
  
      }, completion: { finished in
  
          fromView?.removeFromSuperview()
          self.selectedIndex = toIndex
          self.view.isUserInteractionEnabled = true
      })
  }
  
  func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -&gt; Bool {
      let tabViewControllers = tabBarController.viewControllers!
      guard let toIndex = tabViewControllers.index(of: viewController) else {
          return false
      }
      animateToTab(toIndex: toIndex)
      return true
  }
  }
  </code></pre>