【iOS】ViewController生命周期

了解ViewController生命周期之前,我们首先认识一下ViewController的结构


UIViewController的结构

视图控制器(ViewController),管理View的层级结构,其自身内置了一个view,可以将view的Controller理解为一个view的container(容器),ta的主要职责有以下几点:

  • 管理View视图的生命周期
  • 响应用户操作
  • 和App整体交互,视图的切换
  • 作为一个容器管理多个Controller和动画

ViewController自身内置的view(UIViewController Default View)就是self.view,把自定义的view通过addSubView:粘贴在这个默认提供的view(self.view)上,就实现了控制器对全部视图的管理,因此可以把视图控制器理解为一个包含多个视图容器

ViewController的生命周期

重点关注以下方法:

方法名称 职能
init ViewController初始化时的一个重载函数
viewDidLoad ViewController内置的默认view创建时调用
viewWillAppear ViewController管理的所有视图即将出现时调用
viewDidAppear ViewController管理的所有视图已经出现时调用
viewWillDisappear ViewController管理的所有视图即将消失时调用
viewDidDisappear ViewController管理的所有视图已经消失时调用
Dealloc ViewController销毁时调用

下面我们将以上方法在程序中重写,观察各个方法被调用的时机:

@implementation ViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.freshView = [[UIView alloc] init];
    self.freshView.backgroundColor = [UIColor magentaColor];
    self.freshView.frame = CGRectMake(0, 0, 266, 277);
    self.freshView.center = self.view.center;
    [self.view addSubview: self.freshView];
    
    UITapGestureRecognizer* gestureTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(hideViewController)];
    [self.freshView addGestureRecognizer: gestureTapRecognizer];
}

//默认视图及其包含的子视图即将在屏幕中出现
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
}    // Called when the view is about to made visible. Default does nothing

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
}     // Called when the view has been fully transitioned onto the screen. Default does nothing

//Controller从屏幕中消失不见时(对应一些销毁的逻辑)
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear: animated];
} // Called when the view is dismissed, covered or otherwise hidden. Default does nothing

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear: animated];
}  // Called after the view was dismissed, covered or otherwise hidden. Default does nothing

- (void) dealloc {
    
}

- (void)hideViewController {
    UIViewController* viewController = [[UIViewController alloc] init];
    viewController.view.backgroundColor = [UIColor systemMintColor];
    
    viewController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController: viewController animated: YES completion: nil];
    
}

@end

在重写的每个方法中都打上断点:

可以看到程序先在viewDidLoad里面加载好控件,

ViewController即将出现时,调用viewWillAppear
ViewController已经出现时,调用viewDidAppear

点击隐藏ViewController事件方法后,

新的viewController即将出现时,调用viewWillDisappear
新的viewController已经出现时,调用viewDidDisAppear

总结

了解了UIViewController的生命周期后,就可以在 合适的时机(重写的方法里) 根据需求自定义想要实现的交互事件、代码逻辑

你可能感兴趣的:(ios,cocoa,xcode,objective-c)