在IOS開發(fā)中創(chuàng)建TabBarController和UINavigationController是很常見的,如果
是手寫代碼創(chuàng)建而不是用Storyboard創(chuàng)建,由于涉及到較多的ViewController(一
般為五個),顯得比較麻煩,并且假如選擇的方法過于笨拙,則會產(chǎn)生大量的“重復(fù)代
碼”。我在實踐的過程中總結(jié)出下面這樣一種創(chuàng)建方法,來避免大量“重復(fù)代碼”的
出現(xiàn)。
在上代碼之前,首先假設(shè)我要做五個ViewController,他們的類名分別為FirstView
Controller、SecondViewController、ThirdViewcontroller、FourthViewContro
ller、FifthViewController?,F(xiàn)在開始上代碼:
NSArray *classNameArray = @[@"FirstViewController",@"SencondViewController",@"ThirdViewController",@"FourthViewController",@"FifthViewController"];
NSArray *titleArray = @[@"first",@"sencond",@"third",@"fourth",@"fifth"];
NSMutableArray *navigationControllerArray = [[NSMutableArray alloc] init];
for (int i=0; i<classNameArray.count; i++) {
UIViewController *viewController = [[NSClassFromString(classNameArray[i]) alloc] init];
//設(shè)置title
viewController.title = titleArray[i];
//設(shè)置tabbarItem圖片
UIImage *normalImage = [UIImage imageNamed:[NSString stringWithFormat:@"btn_%@_正常",titleArray[i]]];
UIImage *selectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"btn_%@_點(diǎn)擊",titleArray[i]]];
if (IOS7) {
viewController.tabBarItem.image = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
viewController.tabBarItem.selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
else {
[viewController.tabBarItem setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:normalImage];
}
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
[array addObject:navigationController];
}
UITabBarController *tabBatController = [[UITabBarController alloc] init];
tabBatController.viewControllers = array;
self.window.rootViewController = tabBatController;
//設(shè)置UITabBarItem屬性
UITabBarItem *item = [UITabBarItem appearance];
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:14.0f]} forState:UIControlStateNormal];
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:20/255.0 green:152/255.0 blue:172/255.0 alpha:1], NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:14.0f]} forState:UIControlStateSelected];
tabBarController.viewControllers = navigationControllerArray;
tabBarController.tabBar.selectionIndicatorImage = [UIImage imageNamed:@"item_selected_background.png"];
tabBarController.tabBar.backgroundImage = [UIImage imageNamed:@"tabbar_background.png"];
以上代碼即可完成TabBarController和UINavigationController的創(chuàng)建,其中IOS7為:#define IOS7 [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 表示版本的判斷