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

gri*_*eak 497 cocoa-touch screen uikit ios

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

目前,我使用:

lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
Run Code Online (Sandbox Code Playgroud)

viewWillAppear:willAnimateRotationToInterfaceOrientation:duration:

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

Cal*_*leb 1051

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

您发布的代码的问题在于您指望视图大小与屏幕的大小相匹配,并且您已经看到并非总是如此.如果您需要屏幕大小,您应该查看代表屏幕本身的对象,如下所示:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
Run Code Online (Sandbox Code Playgroud)

拆分视图更新:在评论中,德米特里问道:

如何在拆分视图中获得屏幕大小?

上面给出的代码报告了屏幕的大小,即使在分屏模式下也是如此.使用分屏模式时,应用程序的窗口会发生变化.如果上面的代码没有提供您期望的信息,那么就像OP一样,您正在查看错误的对象.但是,在这种情况下,你应该看一下窗口而不是屏幕,如下所示:

CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • 方向确实在视图控制器级别进行管理.请参阅[管理View Controller的界面方向](http://tinyurl.com/6yso8zt).所以是的,请查看视图控制器的interfaceOrientation属性.顺便说一句,你询问了屏幕大小,这就是我给你看的内容,但是为了显示你的内容你应该使用窗口的界限或屏幕的applicationFrame,这取决于你正在做什么. (7认同)
  • 但请注意,这会返回以磅为单位测量的值.因此,如果您期望以像素为单位的屏幕分辨率,结果将是不正确的,您应该将结果乘以"[UIScreen scale]". (3认同)
  • 有人指出,既然[一个CGRect可以有负宽度或高度](http://bit.ly/1yu5lDs),我们应该使用`CGRectGetWidth()`和`CGRectGetHeight()`而不是直接访问`size`字段在矩形中.我认为它不一定是屏幕矩形的问题,但我想这是需要注意的事情. (3认同)
  • 值得注意的是,这会返回*full*屏幕宽度而不填充.只需从这些结果中减去应用程序的填充(通常每侧20个),即可获得大多数元素的"可用"空间 (2认同)
  • @NickDaugherty是的,这就是重点 - OP需要屏幕尺寸.将对象放在屏幕上的位置完全取决于您,取决于您正在构建的应用程序类型.例如,如果您正在显示照片或游戏界面,则可能根本不需要任何填充. (2认同)

Ege*_*nar 63

小心,[UIScreen mainScreen]也包含状态栏,如果你想检索应用程序的框架(不包括状态栏),你应该使用

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

+ (CGFloat) window_width   {
    return [UIScreen mainScreen].applicationFrame.size.width;
}
Run Code Online (Sandbox Code Playgroud)

  • 因为不推荐使用applicationFrame,所以替换为`return [[UIScreen mainScreen] bounds] .size.width;` (6认同)
  • 在ios 9.0中弃用 (3认同)

Mar*_*lme 42

我已将上述一些Objective-C答案翻译成Swift代码.每个翻译都会继续引用原始答案.

主要答案

let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
Run Code Online (Sandbox Code Playgroud)

简单的功能答案

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

func windowWidth() -> CGFloat {
    return UIScreen.mainScreen().applicationFrame.size.width
}
Run Code Online (Sandbox Code Playgroud)

设备方向答案

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
}
Run Code Online (Sandbox Code Playgroud)

记录答案

let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")
Run Code Online (Sandbox Code Playgroud)


Luk*_*ice 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;
} 
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望使用属性screen.applicationFrame而不是screen.bounds来处理状态栏. (6认同)
  • 你默认得到0,0?当我记录fullScreenRect时,它给了我:{{8.03294e-35,3.09816e-40},{480,320}}.我选择用CGRect初始化temp = CGRectZero; (4认同)

A R*_*ser 15

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

#define DEVICE_SIZE [[[[UIApplication sharedApplication] keyWindow] rootViewController].view convertRect:[[UIScreen mainScreen] bounds] fromView:nil].size
Run Code Online (Sandbox Code Playgroud)

无论器件方向如何,上述常数应返回正确的大小.然后获取尺寸就像:

lCurrentWidth = DEVICE_SIZE.width;
lCurrentHeight = DEVICE_SIZE.height;
Run Code Online (Sandbox Code Playgroud)


mem*_*ons 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];
Run Code Online (Sandbox Code Playgroud)


Ole*_*nov 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;
}
Run Code Online (Sandbox Code Playgroud)


Gau*_*ani 8

NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);
Run Code Online (Sandbox Code Playgroud)


bad*_*esh 7

利用这些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)
    
}
Run Code Online (Sandbox Code Playgroud)


kar*_*yan 5

在这里,我已经更新了迅速3

自iOS 9起不推荐使用applicationFrame

很快,他们删除了()并且更改了一些命名约定,您可以在这里参考链接

func windowHeight() -> CGFloat {
    return UIScreen.main.bounds.size.height
}

func windowWidth() -> CGFloat {
    return UIScreen.main.bounds.size.width
}
Run Code Online (Sandbox Code Playgroud)


lea*_*vez 5

现代答案:

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

使用应用程序主窗口的大小:

UIApplication.shared.delegate?.window??.bounds.size ?? .zero
Run Code Online (Sandbox Code Playgroud)

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

UIApplication.shared.statusBarFrame.width
Run Code Online (Sandbox Code Playgroud)

使用的旧解决方案UIScreen.main.bounds将返回设备的边界。如果您的应用在拆分视图模式下运行,则会获得错误的尺寸。

self.view.window 当应用程序包含 2 个或更多窗口并且窗口尺寸较小时,最热门的答案中的尺寸可能会错误。