问题
The default behavior of a UITabBarController is to pop the contained UINavigationController to the root view controller when a particular tab is tapped a second time. I have a particular use case where I'm wanting this to not work automatically, and I'm having a hard time figuring out how to prevent this.
Has anyone run into this, and if so, what did you do? Do I need to subclass UINavigationController and override popToRootViewController or is there a simpler way?
回答1:
Use the tabBarController:shouldSelectViewController: method of the UITabBarControllerDelegate protocol.
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
return viewController != tabBarController.selectedViewController;
}
Don't forget to set the delegate of the tab bar controller to the object that actually implements this delegate method.
回答2:
this is what I did:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
if ([[tabBarController viewControllers] objectAtIndex:[tabBarController selectedIndex]] == viewController)
return NO;
return YES;
}
regards
回答3:
Update Swift 4.1
Stop Double Tap for all tabs.
extension TabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//for blocking double tap on all tabs.
return viewController != tabBarController.selectedViewController
}}
Stop Double Tap on only one specific tab. Here it's for 3rd Tab.
extension TabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//for blocking double tap on 3rd tab only
let indexOfNewVC = tabBarController.viewControllers?.index(of: viewController)
return ((indexOfNewVC != 2) ||
(indexOfNewVC != tabBarController.selectedIndex))
}}
Hope it helps...
Thanks!!!
回答4:
This behavior is a little strange, but a handy shortcut in case of deep hierarchy!
You can implement following UITabBarControllerDelegate methods to disable this system wide shortcut:
#pragma mark -
#pragma mark UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tbc shouldSelectViewController:(UIViewController *)vc {
UIViewController *tbSelectedController = tbc.selectedViewController;
if ([tbSelectedController isEqual:vc]) {
return NO;
}
return YES;
}
回答5:
Here is the Swift 3 version:
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return viewController != tabBarController.selectedViewController
}
来源:https://stackoverflow.com/questions/1849975/prevent-automatic-poptorootviewcontroller-on-double-tap-of-uitabbarcontroller