views:

401

answers:

2

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!

+6  A: 

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.

Alan Rogers
actually, this doesn't work when the ipad is oriented landscape.. i.e., if my simulator is running landscape then it still returns 768 (instead of 1024). do you think i should have an if statement that checks orientation in that case or is there a better way to get width?
Shnitzel
Damn --looks like you are correct; I've updated my answer with some more ideas.
Alan Rogers
I ended up just using "CGFloat width = CGRectGetWidth(self.view.bounds);" in my method (no need for didRotateFromInterfaceOrientation)... so atleast self.view.bounds takes into account orientation. thanks!!
Shnitzel
+2  A: 
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);
thyrgle