Obtaining the same screen width and height for portrait and landscape mode

I 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 display of the same width = 768 and height = 1024 for both portrait and landscape mode.

+6
source share
4 answers

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

And one way to define macros for the same as suggested here is 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)
+16
source

This is because you use mainScreen and do not take device orientation into account at all.

It will eventually return the same value all the time if you do not implement a method that registers 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 } 
0
source

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

If you rotate the device, you will never get a new width and height in didRotateToInterfaceOrientation.

you need to override the viewWillLayoutSubviews method, where you get the new width and height, and you can check there if the device orientation has changed, you can use the new dimension. Since viewWillLayoutSubviews will be called every time the view changes, so before implementing the function, please keep in mind and read the Apple documentation.

0
source

try to get height and width from applicationFrame

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

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

0
source

Source: https://habr.com/ru/post/949296/


All Articles