Getting same screen width and height for portrait and landscape mode
Asked Answered
C

4

6

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..

Crum answered 12/7, 2013 at 9:6 Comment(1)
duplicate with this answerPapyrus
G
16

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)
Gutbucket answered 12/7, 2013 at 9:17 Comment(0)
P
0

That's because you are using mainScreen and do not take into account the devices orientation at all.

It's going to end up returning the same value all the time unless you implement a method logging it in all orientations.

Try something like this :

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) 
{       
//log here

} else {
// log here
}
Peterec answered 12/7, 2013 at 9:11 Comment(0)
D
0

Do you want to get the width height when you are rotating the device or when you run the application in landscape mode?

if you are rotating the device then you will never get the new width and height in didRotateToInterfaceOrientation.

you need to override the method viewWillLayoutSubviews, where you will get the new width and height and you can check there if device orientation changed you can use the new dimension. Because viewWillLayoutSubviews will be called everytime a view will change, so please be aware and read the Apple documentation before implementing the function.

Dactylo answered 12/7, 2013 at 9:22 Comment(0)
M
0

try get your height and width from applicationFrame

var h = UIScreen.mainScreen().applicationFrame.size.height

var w = UIScreen.mainScreen().applicationFrame.size.Width

Messinger answered 15/1, 2015 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.