Search code examples
iosobjective-corientationuiinterfaceorientation

Getting same screen width and height for portrait and landscape mode


I have used this code to get screen width and screen height,

    float scaleFactor = [[UIScreen mainScreen] scale];
    CGRect screen = [[UIScreen mainScreen] bounds];
    CGFloat widthInPixel = screen.size.width * scaleFactor;
    CGFloat heightInPixel = screen.size.height * scaleFactor;

    NSLog(@"%f",widthInPixel);
    NSLog(@"%f",heightInPixel);

and

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    NSLog(@"screenBounds W %f",screenBounds.size.width);
    NSLog(@"screenBounds H %f",screenBounds.size.height);

But its showing same width= 768 and height=1024 for both the portrait and landscape mode..


Solution

  • This will help you with good explanation - How to get orientation-dependent height and width of the screen?

    And one of way to define macros for the same as suggested Here's a handy macro:.

    #define SCREEN_WIDTH (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
    #define SCREEN_HEIGHT (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)