天天看點

iOS入門-07UIViewController概述示例

概述

UIViewController作為頁面和Android中的Activity以及Flutter中的Route意義相同,每一個UIViewController相當于一個頁面。

本文重點

  • UIViewController建立
  • UIViewController生命周期
  • UIViewController跳轉

示例

UIViewController建立

在日常開發中我們能夠操作的整個應用程式的啟動類為AppDelegate,而建立工程中ViewController則是第一個頁面,我們什麼都不用處理隻要從ViewController開始寫起就可以了。ViewController作為整個app的首頁面也是第一個頁面。當然如果你是在想換掉它也是可以的,自己去寫一個類繼承UIViewController然後添加為根視圖控制器中。

一個簡單的例子:從一個頁面跳轉到另一個頁面,代碼如下很簡單,主要看注釋并自己運作了解各個生命周期函數調用的時機。

第一個頁面:

#import "ViewController.h"
#import "SecondViewController.h"

@interface ViewController ()

@end

@implementation ViewController
//頁面第一次加載時調用,隻調用一次
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"viewDidLoad");
    //添加個button,點選跳轉到新頁面
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    btn.frame = CGRectMake(40, 40, 100, 50);
    
    [btn setTitle:@"to second" forState:UIControlStateNormal];
    //給button添加點選事件
    [btn addTarget:self action:@selector(click) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:btn];
}

-(void) click{
    //将要跳轉新頁面
    SecondViewController* sVC = [SecondViewController new];
    //設定新頁面是全屏
    sVC.modalPresentationStyle = UIModalPresentationFullScreen;
    //跳轉到新頁面
    [self presentViewController:sVC animated:YES completion:nil];
}

//視圖将顯示
-(void) viewWillAppear:(BOOL)animated{
    NSLog(@"viewWillAppear");
}
//視圖顯示瞬間
-(void) viewDidAppear:(BOOL)animated{
    NSLog(@"viewDidAppear");
}
//視圖将消失
-(void) viewWillDisappear:(BOOL)animated{
    NSLog(@"viewWillDisappear");
}
//視圖消失瞬間
-(void) viewDidDisappear:(BOOL)animated{
    NSLog(@"viewDidDisappear");
}

//記憶體過低警告接受函數
-(void) didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    
}
@end
           

第二個頁面:

建立一個新UIViewController檔案很簡單,如下操作

選中要建立檔案的目标檔案夾,本例子中使用根檔案夾,然後File->New->File

iOS入門-07UIViewController概述示例

然後選擇如下

iOS入門-07UIViewController概述示例

點選Next

iOS入門-07UIViewController概述示例

ok,建立完畢,如下

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //添加一個有顔色的view
    UIView* view = [UIView new];
    
    view.frame = CGRectMake(100, 100, 100, 100);
    
    view.backgroundColor = [UIColor redColor];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:view];
}

//點選螢幕任意一點出發此回調
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //退出目前頁面
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end