如何在 iOS 中获取屏幕的尺寸?
目前,我使用:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
在 viewWillAppear:
和 willAnimateRotationToInterfaceOrientation:duration:
我第一次获得整个屏幕尺寸。我第二次得到屏幕减去导航栏。
如何在 iOS 中获取屏幕的尺寸?
您发布的代码的问题是您指望视图大小与屏幕大小相匹配,而且正如您所见,情况并非总是如此。如果您需要屏幕尺寸,您应该查看代表屏幕本身的对象,如下所示:
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
拆分视图更新:在评论中,德米特里问:
如何在拆分视图中获取屏幕大小?
上面给出的代码报告屏幕的大小,即使在分屏模式下也是如此。当您使用分屏模式时,您的应用程序的窗口会发生变化。如果上面的代码没有为您提供您期望的信息,那么就像 OP 一样,您正在查看错误的对象。但是,在这种情况下,您应该查看窗口而不是屏幕,如下所示:
CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;
斯威夫特 4.2
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height
// split screen
let windowRect = self.view.window?.frame
let windowWidth = windowRect?.size.width
let windowHeight = windowRect?.size.height
小心,[UIScreen mainScreen] 也包含状态栏,如果您想检索应用程序的框架(不包括状态栏),您应该使用
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
return [[UIScreen mainScreen] bounds].size.width;
我已经将上面的一些 Objective-C 答案翻译成 Swift 代码。每个翻译都参考原始答案进行。
主要答案
let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
func windowHeight() -> CGFloat {
return UIScreen.main.bounds.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.main.bounds.size.width
}
let screenHeight: CGFloat
let statusBarOrientation = UIApplication.shared.statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != .portrait
&& statusBarOrientation != .portraitUpsideDown) {
screenHeight = UIScreen.main.bounds.size.width
} else {
screenHeight = UIScreen.main.bounds.size.height
}
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")
return UIScreen.mainScreen().bounds].size.width
我以前使用过这些方便的方法:
- (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;
}
我意识到这是一篇旧文章,但有时我发现#define 像这样的常量很有用,所以我不必担心:
#define DEVICE_SIZE [[[[UIApplication sharedApplication] keyWindow] rootViewController].view convertRect:[[UIScreen mainScreen] bounds] fromView:nil].size
无论设备方向如何,上述常量都应返回正确的大小。然后获取尺寸很简单:
lCurrentWidth = DEVICE_SIZE.width;
lCurrentHeight = DEVICE_SIZE.height;
获取设备尺寸并考虑方向非常非常容易:
// 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];
UIAlertView
将自身作为 keyWindow 的 rootViewController 视图插入。我有避免极端情况的逻辑,因为如果警报视图启动,则用户无法与键盘交互,因此当时通常不需要抓取键盘框架。
我们还必须考虑设备的方向:
CGFloat screenHeight;
// it is important to do this after presentModalViewController:animated:
if ([[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortraitUpsideDown){
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
}
else{
screenHeight = [UIScreen mainScreen].applicationFrame.size.width;
}
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);
利用这些Structs
了解有关 Swift 3.0 中当前设备的有用信息
struct ScreenSize { // Answer to OP's question
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType { //Use this to check what is the device kind you're working with
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_SE = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_7 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_7PLUS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPHONE_X = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
}
struct iOSVersion { //Get current device's iOS version
static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
static let iOS7 = (iOSVersion.SYS_VERSION_FLOAT >= 7.0 && iOSVersion.SYS_VERSION_FLOAT < 8.0)
static let iOS8 = (iOSVersion.SYS_VERSION_FLOAT >= 8.0 && iOSVersion.SYS_VERSION_FLOAT < 9.0)
static let iOS9 = (iOSVersion.SYS_VERSION_FLOAT >= 9.0 && iOSVersion.SYS_VERSION_FLOAT < 10.0)
static let iOS10 = (iOSVersion.SYS_VERSION_FLOAT >= 10.0 && iOSVersion.SYS_VERSION_FLOAT < 11.0)
static let iOS11 = (iOSVersion.SYS_VERSION_FLOAT >= 11.0 && iOSVersion.SYS_VERSION_FLOAT < 12.0)
static let iOS12 = (iOSVersion.SYS_VERSION_FLOAT >= 12.0 && iOSVersion.SYS_VERSION_FLOAT < 13.0)
static let iOS13 = (iOSVersion.SYS_VERSION_FLOAT >= 13.0 && iOSVersion.SYS_VERSION_FLOAT < 14.0)
static let iOS14 = (iOSVersion.SYS_VERSION_FLOAT >= 14.0 && iOSVersion.SYS_VERSION_FLOAT < 15.0)
static let iOS15 = (iOSVersion.SYS_VERSION_FLOAT >= 15.0 && iOSVersion.SYS_VERSION_FLOAT < 16.0)
}
在这里我更新了 swift 3
从 iOS 9 弃用的 applicationFrame
在 swift 三中,他们删除了 () 并且更改了一些命名约定,您可以参考这里 Link
func windowHeight() -> CGFloat {
return UIScreen.main.bounds.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.main.bounds.size.width
}
现代答案:
如果你的应用支持 iPad 上的拆分视图,这个问题就会变得有点复杂。您需要窗口的大小,而不是屏幕的大小,它可能包含 2 个应用程序。窗口的大小在运行时也可能会有所不同。
使用应用程序主窗口的大小:
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
注意:上述方法在启动时可能会在窗口成为关键窗口之前得到错误的值。如果您只需要宽度,非常推荐以下方法:
UIApplication.shared.statusBarFrame.width
使用 UIScreen.main.bounds
的旧解决方案将返回设备的边界。如果您的应用程序在拆分视图模式下运行,则会得到错误的尺寸。
当应用程序包含 2 个或更多窗口并且窗口尺寸较小时,最热门答案中的 self.view.window
可能会出现尺寸错误。
如果您想要屏幕宽度/高度而不考虑设备方向(适用于调整从横向启动的仅纵向视图控制器):
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
}
这些作为标准功能包含在:
https://github.com/goktugyil/EZSwiftExtensions
iOS 13+ 答案 (source of the code finding the key window):
guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
return
}
let windowWidth = window.frame.width
let windowHeight = window.frame.height
CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;
迅捷3.0
宽度
UIScreen.main.bounds.size.width
身高
UIScreen.main.bounds.size.height
对于 iPad 拆分窗口,[[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;
[UIScreen scale]
。CGRectGetWidth()
和CGRectGetHeight()
,而不是直接访问矩形中的size
字段。我认为屏幕矩形永远不会成为问题,但我认为这是需要注意的事情。