IOS TabBarController中判斷是否應該跳轉到登陸界面

開發過程當中在TabBarController中不少時候有一些登陸以後才能夠的操做app

這個時候須要在AppDelegate中判斷是否登陸,試過2種方法:ide

第一種:代理

  1. 設置UITabBarController的代理爲appdelegate以下:tabBar.delegate = self;
  2. 而後在interface後面寫上代理<UITabBarControllerDelegate>
  3. 實現代理裏面的- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController方法
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSLog(@"--tabbaritem.title--%@",viewController.tabBarItem.title);
     
    //這裏我判斷的是當前點擊的tabBarItem的標題
    if ([viewController.tabBarItem.title isEqualToString:@"個人"]) {
        //若是用戶ID存在的話,說明已登錄
        if (USER_ID) {
            return YES;
        }
        else
        {
            //跳到登陸頁面
            LoginViewController *login = [[LoginViewController alloc] init];
            //隱藏tabbar
            login.hidesBottomBarWhenPushed = YES;
            [((UINavigationController *)tabBarController.selectedViewController) pushViewController:login animated:YES];
             
            return NO;
        }
    }
    else
        return YES;
}

這種方法在進入tabBarController中跳轉時沒有問題,可是跳轉到LoginViewController中取消登陸,返回到tabBarController中這個方法就不執行了。code

第二種:開發

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    
    if ([window.rootViewController isKindOfClass:NSClassFromString(@"CYXTabBarController")]) {
        
        UITabBarController * tabVC = (UITabBarController *)window.rootViewController;
        
        if (tabVC.selectedIndex == 3) {
            if (USER_ID) {
                //跳到登陸頁面
                UIStoryboard *loginSB = [UIStoryboard storyboardWithName:@"LoginViewController" bundle:nil];
                LoginViewController *loginVC = [loginSB instantiateInitialViewController];
                self.window.rootViewController = loginVC;
            }
            return UIInterfaceOrientationMaskPortrait;//返回能夠設置是否容許屏幕旋轉(這裏是不容許)
        }
    }
            
    return UIInterfaceOrientationMaskPortrait;
            
}

第二種方法能夠完美解決問題! 關注新平臺:http://www.toutiao.com/m51416718261/get

關注訂閱號:從小就壞it

相關文章
相關標籤/搜索