All Articles

iOS Device Rotation Methods

There are a few ways of being notified when the orientation of your iOS device has changed.

viewWillTransitionTo

func viewWillTransition(to size: CGSize,
                   with coordinator: UIViewControllerTransitionCoordinator)

This method is called before the size of the current/presented view controller’s view is changed.

For example, if you have MainViewController displayed and viewWillTransition() is called, you can grab the new size of the view by referencing the size that comes from the parameter, and change any subview sizes.

https://developer.apple.com/documentation/uikit/uicontentcontainer/1621466-viewwilltransitiontosize

Subscribe to orientationDidChangeNotification notification

Another handy way to know when the physical orientation of your device has changed is by listening to the orientationDidChangeNotification.

With the notification pattern, your object (let’s say, MainViewController) subscribes itself for a specific notification. In this case, it would be the orientationDidChangeNotification. It can be subscribed to using the method below, which is part of the NotificationCenter class. Call this from your MainViewController.

func addObserver(_ observer: Any,
      selector aSelector: Selector,
      name aName: NSNotification.Name?,
      object anObject: Any?)

https://developer.apple.com/documentation/uikit/uidevice/1620025-orientationdidchangenotification