How to detect orientation change?

David picture David · Sep 4, 2014 · Viewed 160.1k times · Source

I am using Swift and I want to be able to load a UIViewController when I rotate to landscape, can anyone point me in the right direction?

I Can't find anything online and a little bit confused by the documentation.

Answer

David picture David · Sep 4, 2014

Here's how I got it working:

In AppDelegate.swift inside the didFinishLaunchingWithOptions function I put:

NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

and then inside the AppDelegate class I put the following function:

func rotated() {
    if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
        print("Landscape")
    }

    if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
        print("Portrait")
    }
}

Hope this helps anyone else!

Thanks!