View Controller Lifecycle
Oct 20, 2022In iOS development, the view controllers are the foundation of the Application's internal structure. The View Controller is the parent of all the views present on a storyboard. Each UIKit application has at least one ViewController. It facilitates the transition between various parts of the user interface.
Functions are called in the following order when a View Controller is added to the view hierarchy:
State Transition Functions
viewDidLoad()
This is called after the view is loaded in to memory, and is commonly thought of as the first method that will be called. Majority of the view configurations and API setups are done here.
viewWillAppear(_: )
This method is called use before the View Controller is added to the view hierarchy. The frame and bounds of the view controller are all set. This function is called each time the view is presented on screen.
viewWillLayoutSubviews()
When the view controller's view is changed in its layout or bounds, then the system will call a viewWillLayoutSubviews. Thus, this function can be called multiple times during the life of the View Controller. Your view controller can override this method to make changes before the view lays out its subviews.
viewDidLayoutSubviews()
viewDidLayoutSubviews is called every time the view is done with autolayout calculations. It is also called if the view is updated, rotated, changed or it’s bounds change. This function is important, especially, when the orientation of device is changed to add some implementation after views are updated.
viewDidAppear(_: )
This function is called just after the View Controller is added to the view hierarchy. The users can see the view at this point, hence, animations can be started here.
Note:viewDidLoad()
is only called once when the view is loaded. Wherever,viewDidappear()
is called everytime the view appears on the screen.
viewWillDisappear(_: )
This is a good place to save user data and cancel network tasks since it is called just before it is about to disappear from the view hierarchy.
viewDidDisappear(_: )
This function is called when the view disappears from the view hierarchy. Thus, the view is already disappeared from the user's view. Tasks like cancelling the data or ending the analytic events can be performed once the view is disappeared.
Conclusion
Understanding the life cycle functions are important to make the most of these functions. Life Cycle functions and state transitions can be summarised as:
Note: This is a highly asked basic interview question.
Congratulations! You have understood the highly important fundamental topic of UIKit.