Sobes.tech
Junior — Middle

Which method allows detecting a change in the device's screen orientation?

sobes.tech AI

Answer from AI

In iOS, to detect changes in screen orientation, you can use the viewWillTransition(to:with:) method in a view controller (UIViewController). This method is called when the size and orientation of the screen change.

Example usage:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { _ in
        let orientation = UIDevice.current.orientation
        if orientation.isLandscape {
            print("Transition to landscape orientation")
        } else if orientation.isPortrait {
            print("Transition to portrait orientation")
        }
    })
}

You can also subscribe to the UIDevice.orientationDidChangeNotification notification to receive updates about device orientation changes.