griotspeak griotspeak - 10 months ago 59
iOS Question

How to get the screen width and height in iOS?

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;


The first time I get the entire screen size. The second time i get the screen minus the nav bar.

Answer Source

How can one get the dimensions of the screen in iOS?

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:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

Update for split view: In comments, Dmitry asked:

How can I get the size of the screen in the split view?

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:

CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;