(Xcode 6, Swift, iOS8)
I am trying to find the device orientation for iPad, and it seems to be needlessly complicated. where am I going wrong?
At first, I tried to use the interfaceOrientation
of my UIViewController, but it is unreliable and deprecated. Apple recommend using the statusBarOrientation property. (1)
statusBarOrientation is of type UIApplication
. I tried to create an instance like so:
var o: UIApplication
and then test:
if (o.statusBarOrientation.isLandscape) { ... }
but received error
Variable 'o' used before being initialized.
Which makes no sense to me at all. Why would I initialize it to a value? I would overwrite the value that I want!?
Then I tried simply creating a variable as recommended in the docs:
var statusBarOrientation: UIInterfaceOrientation
but on a trace:
statusBarOrientation = (UIKit.UIInterfaceOrientation) (0xa0)
So I tried to subclass UIApplication, and access the property through my subclass.
From here, more complexity. It appears that "Every app must have exactly one instance of UIApplication (or a subclass of UIApplication)." (2)
This led me to the following post, which seems to create a Main
routine in Swift?!
Subclass UIApplication with Swift
Again, my goal is to grab the current device orientation, and test it in a conditional. Pseudocoded:
var o = (get device orientation)
if (o == portrait ) { ... } else { ... }
As you can see, I'm in the weeds... any help would be greatly appreciated.
EDIT: I did manage to get it sort-of working with the following:
var o = UIApplication.sharedApplication().statusBarOrientation;
if (o.isLandscape) { ...
however, on initial load, when the device is rotated to landscape, o.isLandscape
is being reported as false
.
Search documentation for "UIViewController," and look in the "Configuring the View Rotation Settings." Under
Discussion
, "Do not use this property for informing layout decisions. Instead, use thestatusBarOrientation
property, described in UIApplication Class Reference."Search documentation for "UIApplication" and look under Subclassing notes