- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//设置根视图控制器
self.window.rootViewController = [ContainerViewController new];
return YES;
}
======================================
@implementation ContainerViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blueColor];
self.loginVC = [[LoginViewController alloc]init];
//添加控制器
[self addChildViewController:self.loginVC];
self.registerVC = [[RegisterViewController alloc]init];
[self addChildViewController:self.registerVC];
self.findPwdVC = [[FindPwdViewController alloc]init];
[self addChildViewController:self.findPwdVC];
//默认显示 登录页面
[self.view addSubview:self.loginVC.view];
//添加切换页面的分段控制器
//segmentedControl必须跟视图显示的层次相一致。
UISegmentedControl *segmentCongtrol = [[UISegmentedControl alloc]initWithItems:@[@"登录",@"注册",@"找回密码"]];
segmentCongtrol.frame = CGRectMake(10, self.view.frame.size.height-45, self.view.frame.size.width - 40 , 40);
[self.view addSubview:segmentCongtrol];
//默认选中的哪一段
segmentCongtrol.selectedSegmentIndex = 0;
//绑定事件
[segmentCongtrol addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
}
-(void)segmentedControlAction:(UISegmentedControl *)sender
{
NSLog(@"%@",self.view.subviews);
//将子视图中的第一个视图移除
[self.view.subviews[0] removeFromSuperview];
//这是一种很麻烦的写法
// switch (sender.selectedSegmentIndex) {
// case 0:
// [self.view insertSubview:_loginVC.view atIndex:0];
// break;
// case 1:{
// [self.view insertSubview:_registerVC.view atIndex:0];
// break;
// }
// case 2:{
// [self.view insertSubview:_findPwdVC.view atIndex:0];
// break;
// }
// }
//管理的是控制器,影响的是页面。
//不需要关注当前是哪一个视图,只要提取其中的一个子控制器的view来显示就可以了。
//通过sender.selectedSegmentIndex获取当前将要显示的控制器,并把控制器的视图插入到self.view中。
//获取到子控制器
[self.view insertSubview: ((UIViewController *)(self.childViewControllers[sender.selectedSegmentIndex])).view atIndex:0];
//将上面的一句话拆分两句话。
// UIViewController *vc = self.childViewControllers[sender.selectedSegmentIndex];
//
// [self.view insertSubview:vc.view atIndex:0];
}