Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPhone/IPad: How to get screen width programmatically?

People also ask

How can I get mobile screen width and height?

Display display = getWindowManager(). getDefaultDisplay(); Point size = new Point(); display. getSize(size); int width = size. x; int height = size.

How do I find my screen size in Swift UI?

main. bounds. height I get the main screen width and height which is constant. So based on the situation you can use any of these two solutions.


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.


CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);

This can be done in in 3 lines of code:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];