David David - 10 days ago 4
iOS Question

How to detect orientation change?

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

OK I had this working before......I was just looking in the wrong place for the output ( that's embarrassing! )

Here's how I got it working:

In AppDelegate.swift inside the "didFinishLaunchingWithOptions" function I put:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil)

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

func rotated()
{
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation))
    {            
        print("landscape")
    }

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

}

Hope this helps anyone else!

Thanks!

Comments