How to get screen size using code on iOS?

How to get the iPhone screen size to give calculation?


Solution 1:

You can use the bounds property on an instance of UIScreen:

CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;  
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;

Most people will want the main screen; if you have a device attached to a TV, you may instead want to iterate over UIScreens and get the bounds for each.

More info at the UIScreen class docs.

Solution 2:

Here is a 'swift' solution: (Updated for swift 3.x)

let screenWidth  = UIScreen.main.fixedCoordinateSpace.bounds.width
let screenHeight = UIScreen.main.fixedCoordinateSpace.bounds.height

This reports in points not pixels and "always reflect[s] the screen dimensions of the device in a portrait-up orientation"(Apple Docs). No need to bother with UIAnnoyinglyLongDeviceOrientation!

If you want the width and height to reflect the device orientation:

let screenWidth  = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height

Here width and height will flip flop values depending on whether the screen is in portrait or landscape.

And here is how to get screen size measured in pixels not points:

let screenWidthInPixels = UIScreen.main.nativeBounds.width
let screenHeightInPixels = UIScreen.main.nativeBounds.height

This also "is based on the device in a portrait-up orientation. This value does not change as the device rotates."(Apple Docs)

Please note that for swift 2.x and lower, you should use UIScreen.mainScreen() instead of UIScreen.main

Solution 3:

Use This Code to fix in iOS8 :

float SW;
float SH;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (( [[[UIDevice currentDevice] systemVersion] floatValue]<8)  && UIInterfaceOrientationIsLandscape(orientation))
{
    SW = [[UIScreen mainScreen] bounds].size.height;
    SH = [[UIScreen mainScreen] bounds].size.width;
}
else
{
    SW = [[UIScreen mainScreen] bounds].size.width;
    SH = [[UIScreen mainScreen] bounds].size.height;
}

Solution 4:

Use the property bounds of UIView if you want to know the size of a certain view or [[UIScreen mainScreen] bounds] if you want to know the screen size of the device.