Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 

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.

like image 415
griotspeak Avatar asked Apr 15 '11 13:04

griotspeak


People also ask

How do I find my screen width and height?

The size of a 16:9 screen depends on how long the screen's diagonal is, as 16:9 is merely the ratio of the screens width to its height. If you have the screens diagonal, you can multiply that measurement by 0.872 to get the screen's width. You can also multiply the diagonal by 0.49 to get the screen's height.

How do you find the current width of a device?

You can get the device screen width via the screen. width property. Sometimes it's also useful to use window. innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.


1 Answers

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; 

Swift 4.2

let screenRect = UIScreen.main.bounds let screenWidth = screenRect.size.width let screenHeight = screenRect.size.height  // split screen             let windowRect = self.view.window?.frame let windowWidth = windowRect?.size.width let windowHeight = windowRect?.size.height 
like image 126
Caleb Avatar answered Sep 28 '22 09:09

Caleb