IPhone/IPad: How to get screen width programmatically?

Shai UI picture Shai UI · Sep 7, 2010 · Viewed 132.8k times · Source

Hi I'm wondering if there's a way to get the width programmatically.

I'm looking for something general enough to accomodate iphone 3gs, iphone 4, ipad. Also, the width should change based on if the device is portrait or landscape (for ipad).

Anybody know how to do this?? I've been looking for a while... thanks!

Answer

Alan Rogers picture Alan Rogers · Sep 7, 2010

Take a look at UIScreen.

eg.

CGFloat width = [UIScreen mainScreen].bounds.size.width;

Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).

UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGFloat width = CGRectGetWidth(self.view.bounds);
}

If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.