Search code examples
iosuiviewuiviewcontrolleruikitlifecycle

UIViewController and UIView Life cycles in iOS


I am concerned to know the life cycles of a View Controller and and View. After Searching a lot on internet, I am still misunderstood with the following concepts:

  • UIViewController controls the UIView or its root view via following callbacks:

    1. ViewDidLoad(_:)
    2. ViewWillAppear(_:)
    3. ViewDidAppear(_:)
    4. ViewWillDisappear(_:)
    5. ViewDidDisappear(_:)
  • UIView controls the subview via following callbacks:

    1. didAddSubview(_:)
    2. willRemoveSubview(_:)
    3. willMove( toSuperView :)
    4. didMoveToSuperView(_:)

There are functions to control the life cycle of UIView in Controller, but is there any function to control the life cycles of UIViewController.

In this article, Any mentioned that both have different life cycles and explained only for view's life cycles. Any help will be much appreciated...


Solution

  • In fact, the life cycle of UIViewController and UIView is not directly related, and they can be treated independently.

    For UIViewController, its life cycle is affected by how it is used:

    1. If used as a childViewController in a container viewController (UINavigationController/UITabBarController/UISplitViewController, etc.), or as window.rootViewController, its lifecycle will be:

      init
      viewDidLoad
      willMoveToParentViewController:
      viewWillAppear:
      didMoveToParentViewController:
      viewDidAppear:
      willMoveToParentViewController:
      viewWillDisappear:
      didMoveToParentViewController:
      viewDidDisappear:
      dealloc
      
    2. If you just use viewController.view to add it to the other views, its life cycle may only be:

      init
      viewDidLoad
      viewWillAppear:
      viewDidAppear:
      dealloc