打开市场上很多的app,可以发现其中的框架结构大同小异,其中最常见的莫过于标签栏控制器+导航栏控制器+视图控制器的框架结构,这类结构有很多种实现方式,纯代码和storyboard 都可以,这里介绍一种我经常使用的方式
一,首先我们需要在applegate中创建当前工程的主窗口,并且创建继承自UITabBarController的标签栏控制器
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [[MainTabBarViewController alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化所有的子控制器
[self setupAllChildViewControllers];
}
* 初始化所有的子控制器
*/
- (void)setupAllChildViewControllers
{
// 1.首页
HomeViewController *home = [[HomeViewController alloc] init];
[self setupChildViewController:home title:@"首页" imageName:@"tabbar_home" selectedImageName:@"tabbar_home_selected"];
// 2.消息
MessageViewController *message = [[MessageViewController alloc] init];
[self setupChildViewController:message title:@"消息" imageName:@"tabbar_message_center" selectedImageName:@"tabbar_message_center_selected"];
// 3.广场
DiscoverViewController *discover = [[DiscoverViewController alloc] init];
[self setupChildViewController:discover title:@"广场" imageName:@"tabbar_discover" selectedImageName:@"tabbar_discover_selected"];
// 4.个人中心
MeViewController *me = [[MeViewController alloc] init];
[self setupChildViewController:me title:@"个人中心" imageName:@"tabbar_profile" selectedImageName:@"tabbar_profile_selected"];
}
/**
* 初始化一个子控制器
* @param childVc 需要初始化的子控制器
* @param title 标题
* @param imageName 图标
* @param selectedImageName 选中的图标
*/
- (void)setupChildViewController:(UIViewController *)childVc title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName
{
// 1.设置控制器的属性
childVc.title = title;
childVc.tabBarItem.image = [UIImage imageNamed:imageName];
childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
// 2.包装一个导航控制器
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:childVc];
[self addChildViewController:nav];
}