本文共 2869 字,大约阅读时间需要 9 分钟。
大部分iOS的app都会用到tabBar,创建代码也都差不多,贴出代码,方便写新项目时过来粘贴代码
#import "MainTabBarViewController.h"
#import "HomeViewController.h"
#import "ClassifyViewController.h"
#import "ShoppingCartViewController.h"
#import "MeViewController.h"
@interface MainTabBarViewController ()
@end
@implementation MainTabBarViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColorwhiteColor];
[selfcreateViewControllers];
[selfcreateItems];
}
- (void)createViewControllers
{
UINavigationController * nc1 = [[UINavigationControlleralloc] initWithRootViewController:[[HomeViewControlleralloc] init]];
UINavigationController * nc2 = [[UINavigationControlleralloc] initWithRootViewController:[[ClassifyViewControlleralloc] init]];
UINavigationController * nc3 = [[UINavigationControlleralloc] initWithRootViewController:[[ShoppingCartViewControlleralloc] init]];
UINavigationController * nc4 = [[UINavigationControlleralloc] initWithRootViewController:[[MeViewControlleralloc] init]];
self.viewControllers =@[nc1,nc2,nc3,nc4];
}
- (void)createItems
{
NSArray *titleArray = @[@"首页",@"商品分类",@"购物车",@"我"];
NSArray *selectImageName =@[@"img_main_homepage_unselected.png",@"img_main_classification_unselected.png", @"img_main_shoppingcart_unselected.png", @"img_main_personal_unselected.png"];
NSArray *unselectImageName =@[@"img_main_homepage_unselected.png",@"img_main_classification_unselected.png", @"img_main_shoppingcart_unselected.png", @"img_main_personal_unselected.png"];
for (int i =0; i < titleArray.count; i++) {
//需要对图片进行单独处理
UIImage *selectImage = [UIImageimageNamed:selectImageName[i]];
selectImage = [selectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIImage *unselectImage = [UIImageimageNamed:unselectImageName[i]];
unselectImage = [unselectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//以上是防止在bar上显示为阴影而不是图片
UITabBarItem *item = self.tabBar.items[i];
item.selectedImage = selectImage;
item.image = unselectImage;
item.title = titleArray[i];
}
[self.tabBarsetBackgroundImage:[UIImageimageNamed:@"img_tabBar_bg_iOS8.png"]];
[[UITabBarItemappearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColorredColor]}forState:UIControlStateSelected];
[[UITabBarItemappearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColordarkGrayColor]}forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end