在iPhone中有什么方法可以取消选择UITabBarController的所有标签吗?即,我的应用程序有一个“主页”,它不属于下面显示的标签栏上的任何标签。现在当用户触摸标签栏上的任何标签时,我想加载相应的标签。这可能吗 ?我已经尝试过了:
self.tabBarController.tabBarItem.enabled = NO; self.tabBarController.selectedIndex = -1;
但这没有帮助。还有其他方法吗?拜托?
答案 0 :(得分:7)
我设法使用KVO技巧完成了这项工作。
这个想法很简单:当UITabBarController尝试设置其selectedViewController属性并立即将其设置为nil时,我们会进行跟踪。
示例代码:
- (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;
}
}
}
}
}
然而,一个小注意事项:tabbar中的第一个视图控制器仍然会被加载(虽然时间很短),因此它的viewDidLoad和viewWillAppear将在启动后被调用。您可能希望添加一些逻辑以防止您可能在这些函数中执行某些初始化,直到由于用户点击(使用例如全局变量或NSNotificationCenter)而“真实”显示该控制器。
答案 1 :(得分:0)
显示未选中标签的标签栏会破坏用户体验。标签栏应始终选择一个元素并显示相应的页面 - 其他一切都令人困惑。
因此,如果你需要展示别的东西,你应该把它作为一个可以被解雇的弹出窗口(即从底部滑动的表格)。
答案 2 :(得分:0)
您可以将UITabBar
添加到视图控制器,并通过UITabBarDelegate
从那里手动管理按钮。您的视图控制器将是“基本”视图,就像主页一样。
这是相对容易做到的,除非您需要UITabBarController
提供的特殊“更多...”视图控制器,您必须自己实现。