基本组件的使用——UINavigationController
作用:在多个ViewController中切换。UINavigationController内部以栈的形式维护一组ViewController,
因此,当导航进入一个新视图的时候,会以push的形式将该ViewController压入栈,当需要返回上一层视图的时候则以pop的形式将当前的ViewController弹出栈顶。
先来看一下我们要实现的效果:
然后是代码:
- (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方法中完成。
现在我们来分析一下navigationcontroller栈中的情况,当初始化完成的时候是这样的:
一切准备就绪之后我们就可以点击to second按钮,这个时候SecondViewController会被压入栈顶,亦即是切换到SecondViewController控制的视图:
同样地,当我们在SecondViewController返回的时候popViewControllerAnimated:方法会被执行,结果是SecondViewController会被弹出栈顶,只剩下FirstViewController:
popViewControllerAnimated:方法总是将栈顶的ViewController弹出,因此它不需要接受ViewController作为参数。
明白了这个原理,UINavigationController的使用其实很简单。