Programmatically change tabBar item?

2019-04-29 03:24发布

I would like to change a TabBar Item, when a User is logged in or not.

For example: i have 5 different tabBar items, all created an Storyboard.

Now i want to change the tarBar with index 2 (or tag == 2) when i user has no account. I would like to load a different rootViewController. The rootViewController is not already an item of my TabBar, i would load a totally different Controller.

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

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

But how to i change the rootViewController?

Should i do it here?

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

    if item.tag == 1 {
        // ?
    }

}

Or should ill create a UINavigationController as RootViewController, and load here the "correct" ViewController as RootViewController?

3条回答
2楼-- · 2019-04-29 03:58

Try this:

self.tabBar.selectedIndex = 0

If you want change of viewController

查看更多
我命由我不由天
3楼-- · 2019-04-29 04:00

You need to replace second tab associated viewcontroller by a new viewcontroller. here is sample code, which may 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 
查看更多
萌系小妹纸
4楼-- · 2019-04-29 04:02

Check if user is logged in and then change view controllers of UITabBarController:

tabbarController.viewControllers?.replaceRange()

Also this may help Set view controllers of UITabBarController in Swift

查看更多
登录 后发表回答