Programmatically change tabBar element?

I would like to change the TabBar Item when the user is logged in or not.

For example: I have 5 different tabBar elements, all created storyboards.

Now I want to change the tarBar with index 2 (or tag == 2) when the user does not have an account. I would like to load another rootViewController. RootViewController is no longer an element of my TabBar, I would load a completely different controller.

What is the best way to do this? I can simply change the icon with:

 self.tabBar.items![0].selectedImage = UIImage(named: "icon_cal_grey") 

But how to change rootViewController?

Should I do it here?

 override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { if item.tag == 1 { // ? } } 

Or do you need to create a UINavigationController as a RootViewController and load the "correct" ViewController here as a RootViewController?

+6
source share
4 answers

Check if the user is registered, and then change the view controllers of the UITabBarController:

 tabbarController.viewControllers?.replaceRange() 

It can also help Install UITabBarController view controllers in Swift.

+3
source

You need to replace the second tab of the viewcontroller with the new view manager. here is a sample code that might help you:

 NSMutableArray *viewControllers = [[NSMutableArray alloc] initWithArray:self.tabBarController.viewControllers]; UIViewController *newVC = [UIViewController new]; UINavigationController *newNav = [[UINavigationController alloc] initWithRootViewController:newVC]; [viewControllers replaceObjectAtIndex:1 withObject:newNav]; self.tabBarController.viewControllers = viewControllers 
+3
source

Try the following:

 self.tabBar.selectedIndex = 0 

If you want to change the viewController view

+1
source

Below is the code for Swift

  let tabViewCntrls : NSMutableArray = ((self.tabBarController?.viewControllers)! as NSArray).mutableCopy() as! NSMutableArray let vcLogin = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginScreen") as! LoginScreen let navRootVC = UINavigationController.init(rootViewController: vcLogin) navRootVC.viewControllers = [vcLogin] tabViewCntrls.replaceObject(at: 1, with: navRootVC) self.tabBarController?.viewControllers = tabViewCntrls as? [UIViewController] 
0
source

Source: https://habr.com/ru/post/1246063/


All Articles