如何在 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:
方法中:
第一次获取整个屏幕大小。第二次获取的是屏幕减去导航栏的大小。
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
UIApplication.shared.statusBarFrame.width
使用UIScreen.main.bounds
的旧解决方案将返回设备的边界。如果您的应用程序在分割视图模式下运行,则会得到错误的尺寸。
self.view.window
在最新的答案中可能会获得错误的大小,当应用程序包含2个或更多窗口并且窗口大小较小时。
CGFloat screenWidthInPoints = [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale;
CGFloat screenHeightInPoints = [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale;
[UIScreen mainScreen].nativeBounds <-- 来自文档 --> 以像素为单位测量的物理屏幕边界矩形。此矩形基于设备处于纵向朝上方向。该值不随设备旋转而改变。
以下是一种获取屏幕尺寸的快捷方式:
print(screenWidth)
print(screenHeight)
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
这些都是标准函数,在以下链接中包含:
iOS 13+的答案(找到关键窗口代码的来源):
guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
return
}
let windowWidth = window.frame.width
let windowHeight = window.frame.height
Swift 3.0
针对宽度
UIScreen.main.bounds.size.width
UIScreen.main.bounds.size.height
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
CGFloat height = [[UIScreen mainScreen]bounds ].size.height;
[[UIScreen mainScreen] bounds]
无法正常工作,请使用[UIApplication sharedApplication].delegate.window.bounds
代替。您可以将这些宏放置在pch文件中,并通过使用“SCREEN_WIDTH”在项目的任何位置使用它们
#define SCREEN_WIDTH ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
以及 "SCREEN_HEIGHT"
#define SCREEN_HEIGHT ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)
使用示例:
CGSize calCulateSizze ;
calCulateSizze.width = SCREEN_WIDTH/2-8;
calCulateSizze.height = SCREEN_WIDTH/2-8;