1

I am new to Swift (using 4 version) and I want to change tab bar item from another view controller (not tab bar controller).

This is my scheme: scheme

From RouterViewController (used for side menu navigation) in didSelectRowAt i'm doing this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let mainViewController = sideMenuController!

    let tabBarController : TabBarController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarController") as! TabBarController

    tabBarController.selectedIndex = indexPath.row
}

It's not throwing any exceptions and debugging shows, that let tabBarController is not null, but it's not changing tab for some reason.

What am I doing wrong?

RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
Vadim
  • 335
  • 3
  • 14

2 Answers2

2

Try this:

self.tabBarController.selectedIndex = 1;
self.tabBarController setSelectedIndex:1];

or

self.tabBarController.selectedViewController = yourViewController;
self.tabBarController setSelectedViewController:yourViewController];
Dixit Akabari
  • 2,419
  • 13
  • 26
0

You can define this variable in the appDelegate:

var window: UIWindow?
let tabViewController = self.window!.rootViewController as! UITabBarController

Now you can use the tabViewController variable in all your code and invoke the methods on this, like the method to change page. For all the methods/variables of the UITableViewController see the documentation at this link:

https://developer.apple.com/documentation/uikit/uitabbarcontroller

I think that change the variable "var selectedIndex: Int" will solve your problem.

Fab
  • 816
  • 8
  • 17