在IOS開發中創建TabBarController和UINavigationController是很常見的,如果
是手寫代碼創建而不是用Storyboard創建,由于涉及到較多的ViewController(一
般為五個),顯得比較麻煩,并且假如選擇的方法過于笨拙,則會產生大量的“重復代
碼”。我在實踐的過程中總結出下面這樣一種創建方法,來避免大量“重復代碼”的
出現。
在上代碼之前,首先假設我要做五個ViewController,他們的類名分別為FirstView
Controller、SecondViewController、ThirdViewcontroller、FourthViewContro
ller、FifthViewController。現在開始上代碼:
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];
//設置title
viewController.title = titleArray[i];
//設置tabbarItem圖片
UIImage *normalImage = [UIImage imageNamed:[NSString stringWithFormat:@"btn_%@_正常",titleArray[i]]];
UIImage *selectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"btn_%@_點擊",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;
//設置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的創建,其中IOS7為:#define IOS7 [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 表示版本的判斷