How to get the screen width and height in iOS? How to get the screen width and height in iOS? ios ios

How to get the screen width and height in iOS?


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.boundslet screenWidth = screenRect.size.widthlet screenHeight = screenRect.size.height// split screen            let windowRect = self.view.window?.framelet windowWidth = windowRect?.size.widthlet windowHeight = windowRect?.size.height


Careful, [UIScreen mainScreen] contains status bar as well, if you want to retrieve the frame for your application (excluding status bar) you should use

+ (CGFloat) window_height   {    return [UIScreen mainScreen].applicationFrame.size.height;}+ (CGFloat) window_width   {    return [UIScreen mainScreen].applicationFrame.size.width;}


I've translated some of the above Objective-C answers into Swift code. Each translation is proceeded with a reference to the original answer.

Main Answer

let screen = UIScreen.main.boundslet screenWidth = screen.size.widthlet screenHeight = screen.size.height

##Simple Function Answer

func windowHeight() -> CGFloat {    return UIScreen.main.bounds.size.height}func windowWidth() -> CGFloat {    return UIScreen.main.bounds.size.width}

##Device Orientation Answer

let screenHeight: CGFloatlet statusBarOrientation = UIApplication.shared.statusBarOrientation// it is important to do this after presentModalViewController:animated:if (statusBarOrientation != .portrait    && statusBarOrientation != .portraitUpsideDown) {    screenHeight = UIScreen.main.bounds.size.width} else {    screenHeight = UIScreen.main.bounds.size.height}

##Log Answer

let screenWidth = UIScreen.main.bounds.size.widthlet screenHeight = UIScreen.main.bounds.size.heightprintln("width: \(screenWidth)")println("height: \(screenHeight)")