基本組件的使用——UINavigationController

做用:在多個ViewController中切換。UINavigationController內部以棧的形式維護一組ViewController,app

所以,當導航進入一個新視圖的時候,會以push的形式將該ViewController壓入棧,當須要返回上一層視圖的時候則以pop的形式將當前的ViewController彈出棧頂。ide

先來看一下咱們要實現的效果:spa

UINavigationController

而後是代碼: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

image

一切準備就緒以後咱們就能夠點擊to second按鈕,這個時候SecondViewController會被壓入棧頂,亦便是切換到SecondViewController控制的視圖:blog

image

一樣地,當咱們在SecondViewController返回的時候popViewControllerAnimated:方法會被執行,結果是SecondViewController會被彈出棧頂,只剩下FirstViewController:get

image

popViewControllerAnimated:方法老是將棧頂的ViewController彈出,所以它不須要接受ViewController做爲參數。it

明白了這個原理,UINavigationController的使用其實很簡單。io

相關文章
相關標籤/搜索