Sobes.tech
Junior — Middle

What happens to the ViewController lifecycle method if you set the backgroundColor property without calling loadView or other view loading methods first?

sobes.tech AI

Answer from AI

If you set the backgroundColor property on a UIViewController without first calling loadView or other view loading methods, the system will automatically call loadView to create the controller's root view.

This happens because the view property of the controller is lazy — it is created only upon first access. Setting backgroundColor actually accesses view, which triggers the view to load.

Therefore, calling backgroundColor without explicitly calling loadView will result in:

  • Automatic creation and loading of the controller's view.
  • Execution of lifecycle methods related to view loading (loadView, viewDidLoad).

Example:

let vc = UIViewController()
vc.view.backgroundColor = .red // The view will be loaded automatically here

This is important to consider to avoid unexpected side effects when working with the ViewController's lifecycle.

What happens to the ViewController lifecycle method… - sobes.tech