1.直接在根視圖控制器上顯示標籤欄和導覽列
只有一個根視圖控制器,在AppDelegate.m檔案中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)lanuchOptions方法中添加如下代碼:
//建立導覽列對象 UINavigationController *pNavigation = [[UINavigationController alloc]initWithRootViewController:self.viewController]; //建立另外一個類的對象 LinAnotherViewController * pAnotherVC = [[LinAnotherViewController alloc]initWithNibName:nil bundle:nil]; //建立Tabbar對象 UITabBarController *pTabBar = [[UITabBarController alloc]init]; //初始化數組,儲存標籤欄的內容 NSArray *pArray = [NSArray arrayWithObjects:pNavigation,pAnotherVC, nil]; //把數組中內容傳遞給標籤欄控制器 pTabBar.viewControllers = pArray; //設定根視圖控制器 self.window.rootViewController = pTabBar;
此時視圖都為空白,可按照之前學習的方法添加相應的控制項、圖片、設定導覽列、標籤欄的屬性等。
2.建立根視圖控制器,顯示切換介面後的標籤欄和導覽列
當需要在頁面跳轉後顯示標籤欄和導覽列,此時應該設定新的根視圖,在它上面編寫建立相應的視圖控制器、導覽列,再添加到標籤欄控制器中。需要實現AppDelegate的委託建立新的根視圖。首先是匯入新視圖的名稱,特別是:LinAppDelegate.h檔案。
#import "LinFirstViewController.h"#import "LinSecondViewController.h"#import "LinThirdViewController.h"//委託協議代理#import "LinAppDelegate.h"
重寫- (void)viewDidLoad方法:
- (void)viewDidLoad{ [super viewDidLoad]; //建立視圖對象和相應的導覽列對象,假設均有導覽列 LinFirstViewController * pFirstVC = [[LinFirstViewController alloc]initWithNibName:nil bundle:nil]; UINavigationController * pFirstNavigation = [[UINavigationController alloc]initWithRootViewController:pFirstVC]; LinSecondViewController * pSecondVC = [[LinSecondViewController alloc]initWithNibName:nil bundle:nil]; UINavigationController * pSecondNavigation = [[UINavigationController alloc]initWithRootViewController:pSecondVC]; LinThirdViewController * pThirdVC = [[LinThirdViewController alloc]initWithNibName:nil bundle:nil]; UINavigationController * pThirdNavigation = [[UINavigationController alloc]initWithRootViewController:pThirdVC]; //初始化數組,儲存導航控制器 NSArray * array = [[NSArray alloc]initWithObjects:pFirstNavigation, pSecondNavigation, pThirdNavigation, nil]; //初始化標籤欄控制器 UITabBarController * pTabBar = [[UITabBarController alloc]init]; //設定標籤欄中視圖控制器(數組) pTabBar.viewControllers = array; //根據委託協議調用方法 [self goInNemView:pTabBar];}//構造委託協議的方法,把標籤控制器放在新的根視圖中- (void)goInNemView:(id)sender{ //擷取當前程式 UIApplication * app = [UIApplication sharedApplication]; //建立應用程式的委派物件 LinAppDelegate * pDelegate = app.delegate; //設定新的根視圖控制器,用委託的方法實現代理 pDelegate.window.rootViewController = sender;}