做用:在多个ViewController中切换。UINavigationController内部以栈的形式维护一组ViewController,app
所以,当导航进入一个新视图的时候,会以push的形式将该ViewController压入栈,当须要返回上一层视图的时候则以pop的形式将当前的ViewController弹出栈顶。ide
先来看一下咱们要实现的效果:spa
而后是代码:3d
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //建立第一个视图 self.firstViewController = [[UIViewController alloc] init]; self.firstViewController.view.backgroundColor = [UIColor whiteColor]; self.firstViewController.title = @"first view"; //在主视图中建立按钮 UIButton *firstBtn = [self createButton:@"to second" target:@selector(push)]; //将按钮添加到视图中 [self.firstViewController.view addSubview:firstBtn]; self.navController = [[UINavigationController alloc] initWithRootViewController:self.firstViewController]; NSLog(@"%@", self.navController.viewControllers); NSLog(@"%@", self.firstViewController); //建立第二个视图 self.secondViewController = [[UIViewController alloc] init]; self.secondViewController.view.backgroundColor = [UIColor whiteColor]; self.secondViewController.title = @"second view"; //在第二个视图中建立按钮 UIButton *secondBtn = [self createButton:@"to first" target:@selector(pop)]; //将按钮添加到第二个视图 [self.secondViewController.view addSubview:secondBtn]; self.window.rootViewController = self.navController; return YES; } #pragma mark - 自定义方法 - (void)push { [self.navController pushViewController:self.secondViewController animated:YES]; } - (void)pop { [self.navController popViewControllerAnimated:YES]; } - (UIButton *)createButton:(NSString *)title target:(SEL)selector { CGRect btnFrame = CGRectMake(100, 100, 100, 25); UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setFrame:btnFrame]; [button setTitle:title forState:UIControlStateNormal]; [button setBackgroundColor:[UIColor lightGrayColor]]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside]; return button; }
整个过程都在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中完成。code
如今咱们来分析一下navigationcontroller栈中的状况,当初始化完成的时候是这样的:orm
一切准备就绪以后咱们就能够点击to second按钮,这个时候SecondViewController会被压入栈顶,亦便是切换到SecondViewController控制的视图:blog
一样地,当咱们在SecondViewController返回的时候popViewControllerAnimated:方法会被执行,结果是SecondViewController会被弹出栈顶,只剩下FirstViewController:get
popViewControllerAnimated:方法老是将栈顶的ViewController弹出,所以它不须要接受ViewController做为参数。it
明白了这个原理,UINavigationController的使用其实很简单。io