如何在iOS中获得屏幕宽度和高度?

时间:2011-04-15 13:46:54

标签: cocoa-touch ios uikit screen

如何在iOS中获得屏幕尺寸?

目前,我使用:

lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
<{1}}和viewWillAppear:

中的

我第一次获得整个屏幕尺寸。第二次我屏幕减去导航栏。

16 个答案:

答案 0 :(得分:1033)

  

如何在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;

Swift 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

答案 1 :(得分:63)

小心,[UIScreen主屏幕]也包含状态栏,如果要检索应用程序的框架(不包括状态栏),则应使用

+ (CGFloat) window_height   {
    return [UIScreen mainScreen].applicationFrame.size.height;
}

+ (CGFloat) window_width   {
    return [UIScreen mainScreen].applicationFrame.size.width;
}

答案 2 :(得分:42)

我已将上述一些Objective-C答案翻译成Swift代码。每个翻译都会参考原始答案。

Main Answer

let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height

Simple Function Answer

func windowHeight() -> CGFloat {
    return UIScreen.mainScreen().applicationFrame.size.height
}

func windowWidth() -> CGFloat {
    return UIScreen.mainScreen().applicationFrame.size.width
}

Device Orientation Answer

var screenHeight : CGFloat
let statusBarOrientation = UIApplication.sharedApplication().statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != UIInterfaceOrientation.Portrait
    && statusBarOrientation != UIInterfaceOrientation.PortraitUpsideDown){
    screenHeight = UIScreen.mainScreen().applicationFrame.size.width
} else {
    screenHeight = UIScreen.mainScreen().applicationFrame.size.height
}

Log Answer

let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")

答案 3 :(得分:39)

我之前使用过这些便利方法:

- (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;
} 

答案 4 :(得分:15)

我意识到这是一篇很老的帖子,但有时我觉得#define这样的常量很有用,所以我不必担心它:

#define DEVICE_SIZE [[[[UIApplication sharedApplication] keyWindow] rootViewController].view convertRect:[[UIScreen mainScreen] bounds] fromView:nil].size

无论设备方向如何,上述常量都应返回正确的大小。然后获得尺寸就像:

lCurrentWidth = DEVICE_SIZE.width;
lCurrentHeight = DEVICE_SIZE.height;

答案 5 :(得分:13)

非常非常容易获得您的设备尺寸以及考虑到方向:

// 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];

答案 6 :(得分:9)

我们也必须考虑设备的方向:

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;
}

答案 7 :(得分:8)

NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);

答案 8 :(得分:4)

此处我更新了 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
}

答案 9 :(得分:3)

如果您想要屏幕宽度/高度,无论设备方向如何(适用于仅从横向方向启动纵向视图控制器):

CGFloat screenWidthInPoints = [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale;
CGFloat screenHeightInPoints = [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale;
  

[UIScreen mainScreen] .nativeBounds&lt; - 来自文档 - &gt;物理屏幕的边界矩形,以像素为单位。此矩形基于纵向方向的设备。该值不会随着设备的旋转而改变。

答案 10 :(得分:3)

利用这些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)

}

答案 11 :(得分:1)

CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;

答案 12 :(得分:1)

swift 3.0

表示宽度

UIScreen.main.bounds.size.width

高度

UIScreen.main.bounds.size.height

答案 13 :(得分:1)

现代答案:

如果您的应用支持在iPad上拆分视图,则此问题会变得有点复杂。您需要窗口大小,而不是屏幕,可能包含2个应用程序。窗口的大小也可能在运行时有所不同。

使用app的主窗口大小:

.something

注意:在启动窗口成为关键窗口之前,上述方法可能会出错。如果您只需要宽度,下面的方法非常推荐

UIApplication.shared.delegate?.window??.bounds.size ?? .zero

使用UIApplication.shared.statusBarFrame.width 的旧解决方案将返回设备的边界。如果您的应用以分屏视图模式运行,则会出现错误的尺寸。

当应用包含2个或更多窗口并且窗口尺寸较小时,最热门答案中的

UIScreen.main.bounds可能会出错。

答案 14 :(得分:0)

对于 iPad 拆分窗口,[[UIScreen mainScreen] bounds] 不起作用,请改用 [UIApplication sharedApplication].delegate.window.bounds

答案 15 :(得分:-2)

您可以将这些宏放在pch文件中,并使用&#34; SCREEN_WIDTH&#34;在项目的任何位置使用它们。

#define SCREEN_WIDTH                ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)

和&#34; SCREEN_HEIGHT&#34;

#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;