Showing posts with label UITabBarControllerDelegate. Show all posts
Showing posts with label UITabBarControllerDelegate. Show all posts

Tuesday, October 5, 2010

How to Disable UITabBarItems but Only Temporarily

User is allowed to use only one UITabBar item, until he has done something e.g. made a selection on list. Other tabs are available after that. Access to tabs can be blocked again e.g. if user chooses to delete current "entry".

Tab access control is done in AppDelegate, since it owns UITabBarController and UITabBarItems. Just set up delegate handling - and that's the key: either there is a delegate to block tabs or there is none for free access:
@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate>
{
   UITabBarController *tabBarController;
}
...
- (BOOL)tabBarController:(UITabBarController *)aTabBarController
shouldSelectViewController:(UIViewController *)viewController
{
  if (
    ([aTabBarController.viewControllers objectAtIndex:1] == viewController) ||
    ([aTabBarController.viewControllers objectAtIndex:2] == viewController)
  )
  {
    // Disable switch to tab 1 and 2
    // Check: otherViewController to enable
    // Check: SomeViewObject to disable
    return NO;
  }
  else
  {
    // Tab ok at index 0
    return YES;
  }
}
Access control can be enabled in any other class/file:
- (void)blockTabAccess
{
  MyAppDelegate *app = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
  app.tabBarController.delegate = app;
  [app SwitchToTab:kTabFirst];
}
Access control can be disabled in any other class/file:
- (void)releaseTabAccess
{
  MyAppDelegate *app = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
  app.tabBarController.delegate = nil;
  [app SwitchToTab:kTabSecond];
}
Some consider it poor design to access AppDelegate directly from "anywhere" and further more to use it to control application state. My defense are the classic a) it's easy b) it's fast c) it works and d) sometimes central control place is a good thing.

Btw this works only as long as you don't need UITabBarControllerDelegate for any other purpose. You have been warned.