How to get screen size using code on iOS?
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.
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