How can one get the dimensions of the screen in iOS?
Currently, I use:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
in viewWillAppear:
and willAnimateRotationToInterfaceOrientation:duration:
The first time I get the entire screen size. The second time i get the screen minus the nav bar.
CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;
The modern answer:
if your app support split view on iPad, this problem becomes a little complicated. You need window's size, not the screen's, which may contain 2 apps. Window's size may also vary while running.
Use app's main window's size:
Note: The method above may get wrong value before window becoming key window when starting up. if you only need width, method below is very recommended:
The old solution using
UIScreen.main.bounds
will return the device's bounds. If your app running in split view mode, it get the wrong dimensions.self.view.window
in the hottest answer may get wrong size when app contains 2 or more windows and the window have small size.The problem with the code that you posted is that you're counting on the view size to match that of the screen, and as you've seen that's not always the case. If you need the screen size, you should look at the object that represents the screen itself, like this:
Update for split view: In comments, Dmitry asked:
The code given above reports the size of the screen, even in split screen mode. When you use split screen mode, your app's window changes. If the code above doesn't give you the information you expect, then like the OP, you're looking at the wrong object. In this case, though, you should look at the window instead of the screen, like this:
Swift 4.2
I realize that this is an old post, but sometimes I find it useful to #define constants like these so I do not have to worry about it:
The above constant should return the correct size no matter the device orientation. Then getting the dimensions is as simple as: