2

I am using a class which extends UITabBarController. I need to set the self.tabBarController.selectedIndex property of my class in order to switch tabs.

Since I want to set this variable/call a method that changes this variable from another class I must have an instance of my custom class which is called TabsController

So far I have looked at these two posts but they involve using the storyboard and I am doing almost everything programmatically, infact this is my entire storyboard:

enter image description here

How do I programmatically solve this problem?

Get Instance Of ViewController From AppDelegate In Swift

Access the instance of a Viewcontroller from another in swift

Cœur
  • 37,241
  • 25
  • 195
  • 267
Foobar
  • 7,458
  • 16
  • 81
  • 161

2 Answers2

3

UITabBarControllers are most often used as applications' rootViewController. While you are not using storyboards, after app launch, if you are setting an instance of TabsController as your app's window's rootViewController, you can refer to this instance from anywhere in your app like so:

if let tabsController = UIApplication.sharedApplication().delegate?.window??.rootViewController as? TabsController {
    tabsController.selectedIndex = 2
}
gravicle
  • 324
  • 2
  • 11
  • Thanks! This code works. Quick question, you say that if I set an instance of `TabsController` to the `rootViewController` then I can refer to that instance by using your code. However, I just tried this code out and it worked, I have not typed any code that sets the `rootViewController`. Is this something that I should be worried about? – Foobar Jul 30 '16 at 01:41
  • @Roymunson The storyboard you have in the question is most probably setting the window's root view controller to be `TabsController`. You can confirm this by looking in your [target's `General` settings tab](http://imgur.com/gallery/YqxcI) where that storyboard is set as the entry point of the application. In the storyboard `TabsController` is [set as the `Initial View Controller`](http://imgur.com/I14mM7Z), which is then set as the root view controller. – gravicle Jul 30 '16 at 05:02
0

you could try this

let controller = self.tabBarController.viewControllers[self.tabBarController.selectedIndex]
xmhafiz
  • 3,482
  • 1
  • 18
  • 26