打開AppStore
,各種類型App
琳瑯滿目。我們最常用的導航就是標簽欄導航了。今天所介紹的是在標簽欄導航中,如何在整個UIApplication
中使用一個UINavigationController
的實例。
我們通常的做法就是在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法中,初始化N
個UIViewController
,N
個UINavigationController
,1個UITabBarController
。用UIViewController
的實例初始化UINavigationController
,得到的N
個UINavigationController
的實例再添加到UITabBarController
的viewControllers
中,UITabBarController
的實例作為self.window.rootViewController
。這樣UITabBarController
的viewControllers
中的每一個UIViewController
都會擁有一個UINavigationController
的實例,但是每個UIViewController
都會擁有一個UINavigationController
的實例并不是同一個。
如果你想一個UIApplication
只擁有一個UINavigationController
的實例,該如何做到呢?
UIViewController *VC1 = [[UIViewController alloc] init];
VC1.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemBookmarks tag:1]];
UIViewController *VC2 = [[UIViewController alloc] init];
VC2.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemHistory tag:2]];
UIViewController *VC3 = [[UIViewController alloc] init];
VC3.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:3]];
UITabBarController *tabViewController = [[UITabBarController alloc] init];
tabViewController.viewControllers = @[VC1, VC2, VC3];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:tabViewController];
self.window.rootViewController = navigationController;
這樣就保證了tabViewController.viewControllers中viewController
擁有同一個navigationController
。
但是需要注意如果要在VC1
, VC2
, VC3
中設置title
,navigationItem.leftBarButtonItem
,navigationItem.rightBarButtonItem
等信息,需要在- (void)viewWillAppear:(BOOL)animated;
或者- (void)viewDidAppear:(BOOL)animated;
方法中調用
self.tabBarController.title = @“主頁”;
self.tabBarController.navigationItem.leftBarButtonItem = ;
self.tabBarController.navigationItem.rightBarButtonItem = ;
進行設置。