在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:
这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。
当前回答
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;
}
注意,[UIScreen mainScreen]包含状态栏,如果你想检索你的应用程序的框架(不包括状态栏),你应该使用
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
我意识到这是一篇旧文章,但有时我发现#定义这样的常量很有用,这样我就不必担心它:
#define DEVICE_SIZE [[[[UIApplication sharedApplication] keyWindow] rootViewController].view convertRect:[[UIScreen mainScreen] bounds] fromView:nil].size
无论设备朝向如何,上述常量都应返回正确的大小。然后获取尺寸就像这样简单:
lCurrentWidth = DEVICE_SIZE.width;
lCurrentHeight = DEVICE_SIZE.height;
CGFloat宽度= [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds].size.height;
iOS 13+的答案(找到键窗口的代码来源):
guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
return
}
let windowWidth = window.frame.width
let windowHeight = window.frame.height