在iOS中如何获得屏幕的尺寸?
目前,我使用:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:
这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。
在iOS中如何获得屏幕的尺寸?
目前,我使用:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:
这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。
当前回答
对于iPad分割窗口,[[UIScreen mainScreen] bounds]不起作用,使用[UIApplication sharedApplication].delegate.window.bounds代替。
其他回答
对于iPad分割窗口,[[UIScreen mainScreen] bounds]不起作用,使用[UIApplication sharedApplication].delegate.window.bounds代替。
这是非常非常容易得到你的设备大小,以及考虑方向:
// 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];
注意,[UIScreen mainScreen]包含状态栏,如果你想检索你的应用程序的框架(不包括状态栏),你应该使用
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
iOS 13+的答案(找到键窗口的代码来源):
guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
return
}
let windowWidth = window.frame.width
let windowHeight = window.frame.height
我以前用过这些方便的方法:
- (CGRect)getScreenFrameForCurrentOrientation {
return [self getScreenFrameForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
- (CGRect)getScreenFrameForOrientation:(UIInterfaceOrientation)orientation {
CGRect fullScreenRect = [[UIScreen mainScreen] bounds];
// implicitly in Portrait orientation.
if (UIInterfaceOrientationIsLandscape(orientation)) {
CGRect temp = CGRectZero;
temp.size.width = fullScreenRect.size.height;
temp.size.height = fullScreenRect.size.width;
fullScreenRect = temp;
}
if (![[UIApplication sharedApplication] statusBarHidden]) {
CGFloat statusBarHeight = 20; // Needs a better solution, FYI statusBarFrame reports wrong in some cases..
fullScreenRect.size.height -= statusBarHeight;
}
return fullScreenRect;
}