問題:今天在項目中遇到這樣一個需求,tabBar上有首頁棚瘟,商家现斋,購物車,個人中心四個模塊偎蘸,當(dāng)點擊商家和購物車時要判斷用戶是否已經(jīng)登錄庄蹋,如果沒有就要跳轉(zhuǎn)到登錄界面,登錄成功后回到指定的控制器迷雪,就拿購物車來說限书,登錄成功后自動跳到購物車界面去
思路:在AppDelegate里面設(shè)置tabBarController的代理為self,在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法中添加監(jiān)聽事件章咧,登錄成功發(fā)送通知我碟,通知信息里面?zhèn)鬟ftabBar的selectIndex值涕烧,至于如何傳遞這個值有很多方法。然后實現(xiàn)- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
方法,跳轉(zhuǎn)到登錄控制器押赊,登錄完成自動跳回
以下是AppDelegate核心代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logSelect:) name:LoginSuccessNotification object:nil];//接收成功的通知
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
//這里我判斷的是當(dāng)前點擊的tabBarItem的標(biāo)題
if ([viewController.tabBarItem.title isEqualToString:@"購物車"])
{
//我的登錄狀態(tài)存放在本地
if ([[[NSUserDefaults standardUserDefaults] objectForKey:LoginStatu] isEqualToString:successLogin]) {
return YES;
}
else//未登錄
{
//跳到登錄頁面亥贸,這里我是用單利來存儲tabbar的selectIndex的辞州,個人習(xí)慣
LoginViewController *login = [[LoginViewController alloc] init];
[MKJRequestHelper shareRequestHelper].selectIndex = @"2";
login.hidesBottomBarWhenPushed = YES;
[((UINavigationController *)tabBarController.selectedViewController) pushViewController:login animated:YES];
return NO;
}
}
//如果是商家
else if([viewController.tabBarItem.title isEqualToString:@"商家"])
{
if ([[[NSUserDefaults standardUserDefaults] objectForKey:LoginStatu] isEqualToString:successLogin])
{
return YES;
}
else
{
//跳到登錄頁面
LoginViewController *login = [[LoginViewController alloc] init];
[MKJRequestHelper shareRequestHelper].selectIndex = @"1";
login.hidesBottomBarWhenPushed = YES;
[((UINavigationController *)tabBarController.selectedViewController) pushViewController:login animated:YES];
return NO;
}
}
return YES;
}
//登錄成功接受到的方法逃贝,讓tabBarConroller直接跳轉(zhuǎn)到你想跳的界面中去
- (void)logSelect:(NSNotification *)text{
_tabBarVC.selectedIndex = [text.userInfo[@"index"]integerValue];
}
登錄控制器的代碼就只有發(fā)送通知就可以了,