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

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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 where that storyboard is set as the entry point of the application. In the storyboard TabsController is set as the Initial View Controller, which is then set as the root view controller.
0

you could try this

let controller = self.tabBarController.viewControllers[self.tabBarController.selectedIndex]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.