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]
To get the status bar (and therefor UI) orientation like the Objective-C code you have, it's simply:
You can also use the
orientation
property of UIDevice:However, that may not match what orientation your UI is in. From the docs:
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
Swift 3, based on Rob's answer
you can use:
SWIFT 3 UPDATE
or
with Notification you can check: IOS8 Swift: How to detect orientation change?
Apple recently got rid of the idea of Landscape vs. Portrait and prefers we use screen size. However, this works:
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. ;)
(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.)