在xcode4.2中提供了一個 Tabbed Application模闆,用于建立一個具有2個按鈕的控制欄的應用。
他的實作方法和《iphone 開發應用程式指南》一書上的思路不一緻。主要的實作,是通過以下幾點來完成的。
1。不建構rootViewController這個控制器。而是通過程式設計方法來實作。主要代碼在AppDelegate.m檔案中的didFinishLaunchingWithOptions展現
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
UIViewController *viewController1 = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];
UIViewController *viewController2 = [[RecommendViewController alloc] initWithNibName:@"RecommendViewController" bundle:nil];
UIViewController *viewController3 = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3,nil];
self.window.rootViewController = self.tabBarController;
//注意這段代碼,隻有設定了tabBarController的委托才能激活次.m檔案中didSelectViewController方法
self.tabBarController.delegate = self;
[self.window makeKeyAndVisible];
return YES;
}
2。核心關鍵代碼解釋:
2.1 代碼:UIViewController *viewController1 = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];
主要目的是通過nib的名稱來建構一個 ViewController。這樣的好處在于:可以通過松耦合的形式,把要顯示的視圖完全獨立出來。這個視圖可以有自己的Controller和xib檔案來控制。比如,這個NewsViewController,就是由NewsViewController.h , NewsViewController.m 和 NewsViewController.xib3個檔案構成一個獨立的元件
2。2 代碼
self.tabBarController = [[UITabBarController alloc] init]; self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3,nil];
就是通過由三個視圖元件構成的數組來初始化這個TabBar,使其擁有3個按鈕選項。
2。3代碼
self.window.rootViewController = self.tabBarController;
由于AppDelegate沒有相應的界面,通過以上代碼,就直接把 tabBarController設定成主程式的rootViewController。這樣就可以在主界面顯示出這個控制條和對于的視圖了。
2。4代碼
self.tabBarController.delegate = self;
通過把tabBarController的委托指向appDelegate,就可以使得我們切入tabBar的事件中去,進行程式設計。
3。切入tabBarController的動作中,進行個性化程式設計。
由于2。4代碼的存在。是以我們可以放開appDelegate.m檔案中原來注釋掉的方法。
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(@"11111111");
}
這樣我們在點選tabBar的每個按鈕時候都會列印出1111111字元串。說明切入成功。
一些體會:
個人認為:通過這種方法來處理TabBar,使得程式各個元件松耦合。結構清晰。代碼簡單。