Getting device orientation in Swift Getting device orientation in Swift ios ios

Getting device orientation in Swift


you can use:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {    var text=""    switch UIDevice.currentDevice().orientation{    case .Portrait:        text="Portrait"    case .PortraitUpsideDown:        text="PortraitUpsideDown"    case .LandscapeLeft:        text="LandscapeLeft"    case .LandscapeRight:        text="LandscapeRight"    default:        text="Another"    }    NSLog("You have moved: \(text)")        }

SWIFT 3 UPDATE

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {    var text=""    switch UIDevice.current.orientation{    case .portrait:        text="Portrait"    case .portraitUpsideDown:        text="PortraitUpsideDown"    case .landscapeLeft:        text="LandscapeLeft"    case .landscapeRight:        text="LandscapeRight"    default:        text="Another"    }    NSLog("You have moved: \(text)")        }

or

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {}

with Notification you can check: IOS8 Swift: How to detect orientation change?

NOTE : didRotateFromInterfaceOrientation is Deprecated Use viewWillTransitionToSize for iOS 2.0 and later

In case of Face up and Face Down this will not work.So we need to use the following.

if UIApplication.shared.statusBarOrientation.isLandscape {     // activate landscape changes} else {     // activate portrait changes}


To get the status bar (and therefor UI) orientation like the Objective-C code you have, it's simply:

UIApplication.sharedApplication().statusBarOrientation

You can also use the orientation property of UIDevice:

UIDevice.currentDevice().orientation

However, that may not match what orientation your UI is in. From the docs:

The value of the property is a constant that indicates the current orientation of the device. This value represents the physical orientation of the device and may be different from the current orientation of your application’s user interface. See “UIDeviceOrientation” for descriptions of the possible values.


Apple recently got rid of the idea of Landscape vs. Portrait and prefers we use screen size. However, this works:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {    if UIDevice.currentDevice().orientation.isLandscape.boolValue {        print("landscape")    } else {        print("portrait")    }}