tut*_*u47 3 iphone objective-c uitabbarcontroller
在iPhone中是否有任何方法可以取消选择UITabBarController的所有选项卡?即,我的应用程序有一个"主页",它不属于下面显示的标签栏上的任何标签.现在当用户触摸标签栏上的任何标签时,我想加载相应的标签.这可能吗 ?我已经尝试过了:
self.tabBarController.tabBarItem.enabled = NO; self.tabBarController.selectedIndex = -1;
但这没有用.还有其他方法吗?请 ?
我已经设法用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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,一个小注意事项:tabbar中的第一个视图控制器仍然会被加载(虽然时间很短),因此它的viewDidLoad和viewWillAppear将在启动后被调用.您可能希望添加一些逻辑以防止您可能在这些函数中执行某些初始化,直到由于用户点击(使用例如全局变量或NSNotificationCenter)而"真实"显示该控制器.
| 归档时间: |
|
| 查看次数: |
3226 次 |
| 最近记录: |