在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 表示版本的判断