title: Switch tab bar view in subview programmatically (custom tab bar controller)
body: <p>Because I want to redesign the tab bar UI, I wrote a custom tab bar controller according to <a href="https://github.com/codepath/ios_guides/wiki/Creating-a-Custom-Tab-Bar" rel="nofollow noreferrer">https://github.com/codepath/ios_guides/wiki/Creating-a-Custom-Tab-Bar</a></p>
  
  <p>In <code>TabBarViewController</code>'s viewDidLoad(), define several subviews corresponding to each tab bar</p>
  
  <pre><code>homeViewController = storyboard.instantiateViewControllerWithIdentifier("HomeViewController")
  ...
  viewControllers = [homeViewController, searchViewController, accountViewController, trendingViewController]
  </code></pre>
  
  <p>and the main method when tapping tab</p>
  
  <pre><code>@IBAction func didPressTab(_ sender: UIButton) {
  
          let previousIndex = selectedIndex
          selectedIndex = sender.tag
  
          tabButtons[previousIndex!].isSelected = false
          let previousVC = viewControllers[previousIndex!]
  
          // remove previous VC
          previousVC.willMove(toParentViewController: nil)
          previousVC.view.removeFromSuperview()
          previousVC.removeFromParentViewController()
  
          // set current VC
          sender.isSelected = true
          let vc = viewControllers[selectedIndex]
  
          addChildViewController(vc)
  
          // Adjust the size to match content view
          vc.view.frame = contentView.bounds
          contentView.addSubview(vc.view)
          vc.didMove(toParentViewController: self)
      }
  </code></pre>
  
  <p>I could set a default tab bar index <code>selectedIndex</code> when the tab bar view is loaded. However, how can I switch to next tab bar in homeViewController (without tapping tab bar buttons)? </p>
  
  <p>This doesn't work in <code>homeViewController</code>
  <code>
  TabBarViewController().tabButtons[2].isSelected = true            TabBarViewController().didPressTab(TabBarViewController().tabButtons[2])
  </code></p>
  
  <p>I'm not sure how to get the running tab controller, set the selectedIndex, and update subview in the subview controllers.</p>