I am using UITabBarController and added tabs using relationship segue from storyboard.
How to hide particular tab according to logged in user role?
I am using UITabBarController and added tabs using relationship segue from storyboard.
How to hide particular tab according to logged in user role?
Nice question!
You need to dig UITabbarController and its members (properties + functions)
Now, focus on these steps to find solution:
viewControllers
(which an array of UIViewController) that stores UIViewControllers for your Tabbar Controller associated using UITabbar items.viewControllers
property of tabbar controller.Here is sample example on application launch:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if var tabController = self.window?.rootViewController as? UITabbarController, var viewControllers = tabController.viewControllers {
let isLoggedIn = <get value from your data storage as bool>
if isLoggedIn {
viewControllers.remove(at: firstIndex) // By considering you need to remove view controller at index first. It will automatically remove tab from tabbar also.
tabController.viewControllers = viewControllers
self.window?.rootViewController = tabController
// further operations to make your root controller visible....
}
}
}
If you want to remove tabs from your tab bar controller do something like this (When your user is not logged in)
NSInteger indexToRemove = 0;
NSMutableArray *tabs = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
[tabs removeObjectAtIndex:indexToRemove];
self.tabBarController.viewControllers = tabs;
when your user logs in
UIViewController *viewController = [[UIViewController alloc] init];
NSMutableArray *tabs = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
[tabs addObject:viewController];
self.tabBarController.viewControllers = tabs;
Swift Version
Remove tab
let indexToRemove = 0
if var tabs = self.tabBarController?.viewControllers {
tabs.remove(at: indexToRemove)
self.tabBarController?.viewControllers = tabs
} else {
print("There is something wrong with tabbar controller")
}
Add tab
let indexToAdd = 2
let vc = UIViewController.init()
if var tabs = self.tabBarController?.viewControllers {
tabs.append(vc) // Append at last index of array
// tabs.insert(vc, at: indexToAdd) // Insert at specific index
self.tabBarController?.viewControllers = tabs
} else {
print("There is something wrong with tabbar controller")
}