Sobes.tech
Junior — Middle

What functions and methods are activated in the root ViewController when changing the screen orientation from vertical to horizontal?

sobes.tech AI

Answer from AI

When changing the screen orientation from portrait to landscape, the following methods and functions are called sequentially on the root UIViewController in iOS:

  • viewWillTransition(to:with:) — notifies the controller about the upcoming size and orientation change.
  • willTransition(to:with:) (on traitCollection) — called to adapt to new conditions.
  • viewWillLayoutSubviews() — called before laying out subviews.
  • viewDidLayoutSubviews() — called after laying out subviews.

If Auto Layout is used, size and position changes of views happen automatically within these methods.

Also, if the supportedInterfaceOrientations or shouldAutorotate methods are supported, the system checks whether the screen can rotate.

Example of overriding a method to handle rotation:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { _ in
        // Update interface for new orientation
    }) { _ in
        // End of animation
    }
}