Sobes.tech
Middle

At what stage does a UIViewController view get information about its size?

sobes.tech AI

Answer from AI

View obtains information about its size in the lifecycle methods of UIViewController related to layout management and display. Specifically, this information is most reliably available after the system has calculated the initial sizes and positions of UI elements, but before they are actually displayed.

The main methods where the view's size is determined:

  • viewWillLayoutSubviews: Called before subviews are laid out. At this point, the view's size is already determined and can be used to configure the layout of subviews.
  • viewDidLayoutSubviews: Called after subviews have been laid out. At this point, the size of the view and its subviews is finalized after the layout cycle.

Additionally, the size can be obtained in viewSafeAreaInsetsDidChange(), which is called when safe areas change.

Using viewDidLoad to get the exact size of the view is not recommended, as at the time of its call, the view hierarchy is not fully set up, and sizes may be incorrect.

Example of obtaining size in viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Check the size of the root view
    let viewSize = view.bounds.size
    print("View size: \(viewSize)")
    // Perform tasks dependent on size:
    // layout subviews, configure scrolling content size, etc.
}

Comparison table of lifecycle methods regarding size availability:

Method Is view size available? When is it called?
viewDidLoad No (imprecise) After view is loaded, before it appears on screen.
viewWillAppear(_:) No (imprecise) Before the view appears on screen.
viewWillLayoutSubviews Yes Before laying out subviews.
viewDidLayoutSubviews Yes After laying out subviews.
viewDidAppear(_:) Yes After the view has appeared on screen.
viewSafeAreaInsetsDidChange() Yes When safe areas change.