I’m trying to programmatically determine the current height and width of my application. I use this:
CGRect screenRect = [[UIScreen mainScreen] bounds];
But this yields a width of 320 and a height of 480, regardless of whether the device is in portrait or landscape orientation. How can I determine the current width and height (i.e. dependent upon the device orientation) of my main screen?
You can use something like
UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)to determine the orientation and then use the dimensions accordingly.HOWEVER, during an orientation change like in UIViewController’s
Use the orientation passed in
toInterfaceOrientationsince the UIApplication’s statusBarOrientation will still point to the old orientation as it has not yet changed (since you’re inside awillevent handler).Summary
There are several related posts to this, but each of them seem to indicate that you have to:
[[UIScreen mainScreen] bounds]to get the dimensions,Links
Working Code
I usually don’t go this far, but you piqued my interest. The following code should do the trick. I wrote a Category on UIApplication. I added class methods for getting the currentSize or the size in a given orientation, which is what you would call in UIViewController’s
willRotateToInterfaceOrientation:duration:.To use the code simple call
[UIApplication currentSize]. Also, I ran the above code, so I know it works and reports back the correct responses in all orientations. Note that I factor in the status bar. Interestingly I had to subtract the MIN of the status bar’s height and width.Other thoughts
You could go about getting the dimensions by looking at the UIWindow’s
rootViewControllerproperty. I’ve looked at this in the past and it similarly reports the same dimensions in both portrait and landscape except it reports having a rotate transform:Not sure how your app works, but if you aren’t using a navigation controller of some kind, you could have a UIView under your main view with the max height / width of parent and grows / shrinks with parent. Then you could do:
[[[[[[[UIApplication sharedApplication] keyWindow] rootViewController] view] subviews] objectAtIndex:0] frame]. That looks pretty intense on one line, but you get the idea.However, it would still be better to do the above 3 steps under the summary. Start messing with UIWindows and you’ll find out weird stuff, like showing a UIAlertView will change UIApplication’s keywindow to point at a new UIWindow that the UIAlertView created. Who knew? I did after finding a bug relying on keyWindow and discovering that it changed like that!