title: Changing Selected Tab in TabViewController Programmatically
body: <p>I have an OS Mac app with two buttons and a Container View in my top level View Controller. I replaced the view controller linked to the Container View with a Tab View Controller. I would like to switch tabs using the buttons in the top level View Controller. The only way I've got it close to working is setting up the button actions as follows:</p>
  <pre><code>@IBAction func selectCompositions(_ sender: NSButton) {
    let tabViewController = self.storyboard?.instantiateController(withIdentifier: &quot;tabViewController&quot;) as!NSTabViewController
    tabViewController.selectedTabViewItemIndex = 2
    let count = tabViewController.selectedTabViewItemIndex
    print(count)
  }
  </code></pre>
  <p>The instantiate call appears to work because, when I added a third tab, the count changed from 1 to 2. This was before I added the instruction to set it. At any rate, the code doesn't change the tab. Instantiating the controller doesn't seem right because the view appears without clicking the button. Is the call only intended to return a link to it and not instantiate a new object? Is there a more straightforward way to do it?</p>
  <p>I tried the answer from this question: <a href="https://stackoverflow.com/questions/28099148/switch-tab-bar-programatically-in-swift">Switch tab bar programmatically in Swift</a>. It generated an error saying it tabViewController was unresolved. I have set the storyboard id of the TabViewController to tabViewController.</p>
  <h2>Update</h2>
  <p>I added:</p>
  <pre><code>self.selectedTabViewItemIndex = 0
  </code></pre>
  <p>to the viewDidLoad method in a class I created and linked to the TabViewController. When I run the app, the index is changed, but the last tab (2) is still shown. When I click on tab 0 in the window, the tab changes, but the display of the index remains the same. It seems like I may be calling the wrong method although none to others seem appropriate.</p>
  <h2>Progress</h2>
  <p>I changed my NSTabViewController class to:</p>
  <pre><code>class TabViewController: NSTabViewController {
  
    override func viewDidLoad() {
      super.viewDidLoad()
      // Do view setup here.
      print(&quot;In TabViewController&quot;)
      switchToDataTab()
    }
  
    func switchToDataTab() {
      Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(switchToDataTabCont), userInfo: nil, repeats: false)
    }  
  
    func switchToDataTabCont(){
      self.selectedTabViewItemIndex = 2
    }
  }
  </code></pre>
  <p>This is an answer from the solution linked above. It works fine in the controller linked to the control, but not in the main controller button action methods. It makes me think I've instantiated a second instance of the class.</p>