According to this answer, you should run your code in viewWillAppear
and/or viewDidLayoutSubviews
. When viewDidLoad
is called, that view controller's view is guaranteed to be loaded into memory, but it is not yet rendered. viewWillAppear
is called when a view is about to be added to an on-screen view hierarchy, as detailed in the Apple developer documentation. At this point, the view controller should be able to access the orientation that the device is in, since its content views will most likely be rendered when viewWillAppear
is called. If your code is still returning the wrong values, you may need to move it into viewDidLayoutSubviews
, which is called whenever the bounds of the current view will change.
Edit: it looks like you will need to flip the width and height values based on the orientation and their relationship to one another, as stated in this answer, although that is in Objective-C. In Swift:
public var width: CGFloat {
//If in landscape mode
if (UIApplication.shared.statusBarOrientation.isLandscape) {
//If in landscape and the width is less than the height (wrong),
//return the height instead of the width
if (UIScreen.main.bounds.width < UIScreen.main.bounds.height) {
return UIScreen.main.bounds.height
}
}
//Else just return the width
return UIScreen.main.bounds.width
}
public var height: CGFloat {
//If in landscape mode
if (UIApplication.shared.statusBarOrientation.isLandscape) {
//If in landscape and the height is greater than the width (wrong),
//return the width instead of the height
if (UIScreen.main.bounds.height > UIScreen.main.bounds.width) {
return UIScreen.main.bounds.width
}
}
//Else just return the height
return UIScreen.main.bounds.height
}