33

Hello i want to get the width and height of my main view. I want the correct value in landscape or portrait mode. I've tried the following:


  NSLog(@"aaa %f", [UIScreen mainScreen].applicationFrame.size.width);
  NSLog(@"zzz %f", self.view.frame.size.width);

These give 300 in landscape and 320 in portrait mode, yes it is larger in portrait mode. So.. my view takes up the whole screen (- status bar) so I expect 480 in landscape mode and 320 in portrait mode. What happened to the rest of the pixels. Do I have to hardcode these values? Thanks.

gyozo kudor
  • 6,284
  • 10
  • 53
  • 80

3 Answers3

104

Do either of the following lines work for you?

[[UIScreen mainScreen] bounds].size.height
[[UIScreen mainScreen] bounds].size.width

I suppose you can subtract the height of the status bar? Maybe i'm not understanding your question

elp
  • 8,021
  • 7
  • 61
  • 120
Omar
  • 1,574
  • 1
  • 9
  • 14
  • 1
    This works it returns the same width and height for both orientations but at least it works. And yes I need to substract the status bar. – gyozo kudor Jan 10 '11 at 12:10
  • @Omar you need an extra `[` before the UIScreen. – Aaron Brager Jan 07 '13 at 19:42
  • 2
    From iOS8 [UIScreen mainScreen].bounds is interface-oriented (look at session "View Controller Advancements in iOS 8" of WWDC 2014), this means that in landscape mode on iOS8 height and width are reversed. – Andr3a88 Mar 19 '15 at 09:12
  • @Andr3a88, Thanks for that additional info. This means that the original answer is even more satisfactory than it was before. – Omar Mar 20 '15 at 22:04
10

Try this :

UIWindow* window = [UIApplication sharedApplication].keyWindow;
NSLog(@"%f",window.frame.size.width);
jithinroy
  • 1,885
  • 1
  • 16
  • 23
6

Useful macros that will give you the correct size based on the device orientation:

#define SCREEN_WIDTH ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
#define SCREEN_HEIGHT ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)
sash
  • 8,423
  • 5
  • 63
  • 74