问题
I have UITabBarController having 5 tabbar buttons. On some activity I want to unhighlight all the tab bat items.
Can anyone help please?
Thank you,
Ankita
回答1:
First of all, I'd like to say that unselecting all tabbaritems is a bad user experience. Chances are high that it won't be accepted into the appstore.
After I said that, I found the answere here. You can accept this answer (if it works!!!) but props should be given to that user. He used a trick in Key Value Observing, and used the following code:
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Create the view controller which will be displayed after application startup
mHomeViewController = [[HomeViewController alloc] initWithNibName:nil bundle:nil];
[tabBarController.view addSubview:mHomeViewController.view];
tabBarController.delegate = self;
[tabBarController addObserver:self forKeyPath:@"selectedViewController" options:NSKeyValueObservingOptionNew context:NULL];
// further initialization ...
}
// This method detects if user taps on one of the tabs and removes our "Home" view controller from the screen.
- (BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
if (!mAllowSelectTab)
{
[mHomeViewController.view removeFromSuperview];
mAllowSelectTab = YES;
}
return YES;
}
// Here we detect if UITabBarController wants to select one of the tabs and set back to unselected.
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (!mAllowSelectTab)
{
if (object == tabBarController && [keyPath isEqualToString:@"selectedViewController"])
{
NSNumber *changeKind = [change objectForKey:NSKeyValueChangeKindKey];
if ([changeKind intValue] == NSKeyValueChangeSetting)
{
NSObject *newValue = [change objectForKey:NSKeyValueChangeNewKey];
if ([newValue class] != [NSNull class])
{
tabBarController.selectedViewController = nil;
}
}
}
}
}
He added the following note:
the first view controller from tabbar still will be loaded (although for a very short time), so its viewDidLoad and viewWillAppear will be called after startup. You may want to add some logic to prevent some initializations you probably may do in these functions until "real" display of that controller as a result of user tap (using for example global variables or NSNotificationCenter).
EDIT: this is for adapting the Apple-UITabbar. You can also create a custom UITabbar.
来源:https://stackoverflow.com/questions/5647756/unhighlight-uitabbaritem-in-uitabbarcontroller