97

I was wondering how I can get the current device orientation in Swift? I know there are examples for Objective-C, however I haven't been able to get it working in Swift.

I am trying to get the device orientation and put that into an if statement.

This is the line that I am having the most issues with:

[[UIApplication sharedApplication] statusBarOrientation]
2
  • What is your problem? Translating that into Swift or getting the values that you expect? Sep 11, 2014 at 20:43
  • 1
    The device orientation does not necessarily match your UI orientation. Casing point - lie your device flat and test your code!
    – Patrick
    Mar 21, 2016 at 17:11

20 Answers 20

78

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
}
2
  • Hmm...what if the user navigates to this view after already rotating, we wouldn't know the starting orientation... Dec 9, 2018 at 22:23
  • In case you're still using this function despite it's deprecated. don't forget to call it's super method in your implementation. i.e.: super.didRotate(from: fromInterfaceOrientation). From the Apple documentation: "Your implementation of this method must call super at some point during its execution."
    – Bocaxica
    Mar 7, 2019 at 10:31
64

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.

5
  • UIApplication.sharedApplication().statusBarOrientation is only on main thread
    – Yair hadad
    Nov 1, 2018 at 13:32
  • 1
    I was using uidevice.current.orientation.isportrait to check the device orientation and change ui of app but it was changing even if a put the device on desk. But thanks to you now its working perfactly fine Apr 16, 2019 at 16:49
  • updated on swift 5.1 -> UIDevice.current.orientation Nov 4, 2019 at 2:01
  • UIDevice.current.orientation.isPortrait does not work if the device orientation is faceup or facedown. Checking the status bar like this answer gives has been consistent and working for me.
    – Austin
    Jan 16, 2020 at 23:03
  • 1
    For people who couldn't make it work: UIDevice.current.orientation also works
    – tpbafk
    Jun 4, 2021 at 13:48
29
struct DeviceInfo {
struct Orientation {
    // indicate current device is in the LandScape orientation
    static var isLandscape: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isLandscape
                : UIApplication.shared.statusBarOrientation.isLandscape
        }
    }
    // indicate current device is in the Portrait orientation
    static var isPortrait: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isPortrait
                : UIApplication.shared.statusBarOrientation.isPortrait
        }
    }
}}

swift4 answer: this is how I do it,

1.works for all kinds of view controller

2.also work when the user rotates the app

3.also for the first time install the app

4
  • 1
    perfect answer! Thanks
    – torap
    Nov 16, 2017 at 15:11
  • Nice but why you write it tow time instead of @objc class var isLandscape: Bool { return !isPortrait } I am not getting something crucial ? ;)
    – Renetik
    Mar 10, 2019 at 19:11
  • Wow it's works perfectly as I won't.. Thank you so much :) Oct 4, 2019 at 10:57
  • How do I know orientation changed?
    – user5306470
    May 22, 2020 at 19:05
28

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")
    }
}
1
  • 8
    I would note with your solution that apple states: "If you override this method in your custom view controllers, always call super at some point in your implementation"
    – Popmedic
    Oct 7, 2015 at 15:07
17

Swift 4:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            print("landscape")
        } else {
            print("portrait")
        }
    }
2
  • What about isFlat orientation? May 2, 2018 at 13:42
  • 4
    Don't forget to call super.viewWillTransition(to: size, with: coordinator) at some point in your overriding function.
    – Bocaxica
    Mar 7, 2019 at 10:33
16

To find current device orientation simply use this code:

UIApplication.sharedApplication().statusBarOrientation

for swift 3.0

UIApplication.shared.statusBarOrientation

2
  • iPad air 1&2 returns incorrect value, iPad 2 and iPhone are correct. I'm really trying to find one that works on all devices but apple made a real mess here! :(
    – Steven B.
    Jan 4, 2017 at 11:32
  • 1
    unlike UIDevice.current.orientation, UIApplication.shared.statusBarOrientation is available on initial load, not just after the screen is rotated.
    – ewizard
    Feb 6, 2018 at 19:59
13

statusBarOrientation is deprecated, so no longer available to use like in above answers

In this code can get orientation without worrying about depreciation. Swift 5 ioS 13.2 Tested 100%

Your application should allow working in both portrait and landscape to use the below code, otherwise, results will be different

windows.first is main window windows.last is your current window

struct Orientation {
    // indicate current device is in the LandScape orientation
    static var isLandscape: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isLandscape
                : (UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape)!
        }
    }
    // indicate current device is in the Portrait orientation
    static var isPortrait: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isPortrait
                : (UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isPortrait)!
        }
    }
}
12

I had issues with using InterfaceOrientation, it worked OK except it wasn't accessing the orientation on loading. So I tried this and it's a keeper. This works because the bounds.width is always in reference to the current orientation as opposed to nativeBounds.width which is absolute.

    if UIScreen.mainScreen().bounds.height > UIScreen.mainScreen().bounds.width {
        // do your portrait stuff
    } else {    // in landscape
        // do your landscape stuff
    }

I call this from willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) and from viewDidLoad but it flexible.

Thanks to zSprawl for the pointer in that direction. I should point out that this is only good for iOS 8 and later.

3
  • does NOT work on iOS 9 & 10 iPads, only initial value is correct, all following values are opposite orientation.
    – Steven B.
    Jan 4, 2017 at 11:42
  • @Steven.B Hmmm... works fine on my iPad Air, iPad 3 and simulator under iOS 9. Also worked with beta testers. Perhaps you are also using other code that is affecting this.
    – bpedit
    Jan 4, 2017 at 17:09
  • This code probably only works when used in a UIViewcontroller, I'm trying to get the orientation & bounds in a custom UIView class but almost every device I test returns different values, when the orientation is correct than the frame or bounds are still wrong.
    – Steven B.
    Jan 5, 2017 at 8:19
12

So, if Apple is deprecating the whole orientation string thing ("portrait","landscape"), then all you care about is the ratio of width to height. (kinda like @bpedit's answer)

When you divide the width by the height, if the result is less than 1, then the mainScreen or container or whatever is in "portrait" "mode". If the result is greater than 1, it's a "landscape" painting. ;)

override func viewWillAppear(animated: Bool) {
    let size: CGSize = UIScreen.mainScreen().bounds.size
    if size.width / size.height > 1 {
        print("landscape")
    } else {
        print("portrait")
    }
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    if size.width / size.height > 1 {
        print("landscape")
    } else {
        print("portrait")
    }
}

(I'm guessing that if you use this approach then you probably don't really care about specifically handling the condition when the ratio is exactly 1, equal width and height.)

1
  • 2
    Nice! Small improvement to your answer: Don't forget to call super.viewWillAppear(animated) and super.viewWillTransition(to: size, with: coordinator) at some point in your overriding functions
    – Bocaxica
    Mar 7, 2019 at 10:27
12

Swift 3+

Basically:

NotificationCenter.default.addObserver(self, selector: #selector(self.didOrientationChange(_:)), name: .UIDeviceOrientationDidChange, object: nil)

@objc func didOrientationChange(_ notification: Notification) {
    //const_pickerBottom.constant = 394
    print("other")
    switch UIDevice.current.orientation {
        case .landscapeLeft, .landscapeRight:
            print("landscape")
        case .portrait, .portraitUpsideDown:
            print("portrait")
        default:
            print("other")
    }
}

:)

2
  • I love this answer. It's very useful for bigger screens like iPad where you can't use func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) as the traitcollection will always be width.regular and height.regular, thus the traitCollection won't change on rotation. In Swift 4 the notification has been renamed to UIDevice.orientationDidChangeNotification.
    – Bocaxica
    Mar 7, 2019 at 10:21
  • 1
    This is what I was looking for. For Swift 4 and above using like this: let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(self.didOrientationChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) Apr 20, 2021 at 20:08
9

Swift 5 – Solution: Check orientation on app start & during device rotation:

// app start
override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let orientation = self.view.window?.windowScene?.interfaceOrientation {
        let landscape = orientation == .landscapeLeft || orientation == .landscapeRight
    }
}

// on rotation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    let landscape = UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight
}
3
  • This answer gets rid of the windows deprecation warning for me in an OS 15 target
    – Jav Solo
    Sep 25, 2021 at 11:19
  • 3
    you are calling super.viewWillAppear instead of super.viewDidAppear Sep 29, 2021 at 10:31
  • Works really well - thanks Mar 17, 2022 at 8:28
6

UIDevice.current.orientation did not work for my compass-type application, because it reports "faceUp" or "faceDown" when the phone is horizontal, regardless of how the screen is oriented. I want to show the direction the user is facing, assuming they're holding the phone in a natural orientation.

UIApplication.shared.statusBarOrientation gave me a deprecated warning "'statusBarOrientation' was deprecated in iOS 13.0: Use the interfaceOrientation property of the window scene instead."

The following did what I needed.

var headingOffset = 0.0
        
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
        
switch windowScene?.interfaceOrientation {
case .portrait:
   headingOffset = 0.0
   print("Reporting orientation as portrait")
case .portraitUpsideDown:
   headingOffset = 180.0
   print("Reporting orientation as portraitUpsideDown")
case .landscapeLeft:
   headingOffset = -90.0
    print("Reporting orientation as landscapeLeft")
case .landscapeRight:
   headingOffset = 90.0
   print("Reporting orientation as landscapeRight")
default:
   headingOffset = 0.0
   print("Reporting orientation as default")
}
1
  • Thank you, this is the only answer that helped me. Been searching for way too long.
    – Ali Pacman
    Feb 21 at 13:15
4

Swift 3, based on Rob's answer

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if (size.width / size.height > 1) {
        print("landscape")
    } else {
        print("portrait")
    }
}
1
  • 2
    Don't forget to call super.viewWillTransition(to: size, with: coordinator) at some point in your overriding function
    – Bocaxica
    Mar 7, 2019 at 10:27
4

I found that the alternative code in Swift for the Obj-C code

if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) 

is

if UIApplication.shared.statusBarOrientation.isLandscape

Note: we are trying to find the status bar orientation is landscape or not. If it is landscape then the if statement is true.

3
   override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    if (toInterfaceOrientation.isLandscape) {
        NSLog("Landscape");
    }
    else {
        NSLog("Portrait");
    }
}
3

Swift 5

Works in SwiftUI and storyboard based app. Also, check rotation and trait handlers:

struct Orientation {
    
    /// true - if landscape orientation, false - else
    static var isLandscape: Bool {
        orientation?.isLandscape ?? window?.windowScene?.interfaceOrientation.isLandscape ?? false
    }
    
    /// true - if portrait orientation, false - else
    static var isPortrait: Bool {
        orientation?.isPortrait ?? (window?.windowScene?.interfaceOrientation.isPortrait ?? false)
    }
    
    /// true - if flat orientation, false - else
    static var isFlat: Bool {
        orientation?.isFlat ?? false
    }
    
    /// valid orientation or nil
    static var orientation: UIDeviceOrientation? {
        UIDevice.current.orientation.isValidInterfaceOrientation ? UIDevice.current.orientation : nil
    }
    
    /// Current window (for both SwiftUI and storyboard based app)
    static var window: UIWindow? {
        guard let scene = UIApplication.shared.connectedScenes.first,
              let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
              let window = windowSceneDelegate.window else {
            return UIApplication.shared.windows.first
        }
        return window
    }
}

class ViewController: UIViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        layoutAll()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        print("viewWillTransition")
        layoutAll()
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        print("traitCollectionDidChange")
        layoutAll()
    }
    
    /// Layout content depending on the orientation
    private func layoutAll() {
        // Layout as you need
        print("layoutAll: isLandscape=\(Orientation.isLandscape), isPortrait=\(Orientation.isPortrait), traitCollection=\(traitCollection)")
    }
}
1

For anyone seeing this past iOS 13:

The most reliable way to me is deprecated now, though it is (still) working:

print(UIApplication.shared.statusBarOrientation.isPortrait)

What seems to be the way to go now:

if UIApplication.shared.windows.first?.
windowScene?.interfaceOrientation.isPortrait ?? true {
    print("Portrait")
} else {
    print("Landscape")
}
1

Keeping it simple:

let orientation = UIApplication.shared.statusBarOrientation.isLandscape ? "landscape" : "portrait"
1

I think the best way to do this in modern Objective C and accounting for now deprecated functions is...

UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]);

In swift, that would be.

UIDevice.current.orientation.isLandscape
0

Try to use horizontalSizeClass & verticalSizeClass:

import SwiftUI

struct DemoView: View {
    
    @Environment(\.horizontalSizeClass) var hSizeClass
    @Environment(\.verticalSizeClass) var vSizeClass
    
    var body: some View {
        VStack {
            if hSizeClass == .compact && vSizeClass == .regular {
                VStack {
                    Text("Vertical View")
                }
            } else {
                HStack {
                    Text("Horizontal View")
                }
            }
        }
    }
}

Found it in this tutorial. Related Apple's documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.