Junior
Tell me about the lifecycle of UIViewController.
sobes.tech AI
Answer from AI
UIViewController goes through the following main stages:
- Initialization: Creating an instance of the controller.
- Loading View: Loading or creating the view associated with the controller (
UIView). - View Appearing: Preparing and displaying the view on the screen.
- View Displayed: The view is fully visible and interacts with the user.
- View Disappearing: The view starts to hide or is removed from the screen.
- View Unloading: The view is removed from memory.
Main lifecycle methods:
init(nibName:bundle:)/required init?(coder:): Initialization of the controller.viewDidLoad(): Called once after the view is loaded into memory.viewWillAppear(_:): Called just before the view appears on the screen.viewDidAppear(_:): Called after the view has fully appeared on the screen.viewWillDisappear(_:): Called just before the view is hidden or removed.viewDidDisappear(_:): Called after the view has been fully hidden or removed.viewWillLayoutSubviews(): Called before the view controller's subviews start to change their size and position.viewDidLayoutSubviews(): Called after the subviews have finished changing their size and position.didReceiveMemoryWarning(): Called when a low memory warning is received.deinit: Called before the memory occupied by the controller instance is released.
Usage example:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Perform one-time view setup here
print("viewDidLoad")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Update UI before the view appears
print("viewWillAppear")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Start animations or other tasks after the view appears
print("viewDidAppear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Save UI state before the view disappears
print("viewWillDisappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Stop tasks that are not needed when the view is not visible
print("viewDidDisappear")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// Configure frames of elements before they are redrawn
print("viewWillLayoutSubviews")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Configure after elements are redrawn
print("viewDidLayoutSubviews")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release resources in low memory situations
print("didReceiveMemoryWarning")
}
deinit {
// Cleanup subscriptions and other resources
print("deinit")
}
}