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

目前,我使用:

lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;

在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:

这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。


当前回答

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

其他回答

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

你所发布的代码的问题是,你指望视图的大小与屏幕的大小相匹配,正如你所看到的,情况并不总是这样。如果你需要屏幕大小,你应该查看代表屏幕本身的对象,如下所示:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

拆分视图更新:在评论中,Dmitry问道:

如何在分屏视图中获取屏幕的大小?

上面给出的代码报告屏幕的大小,即使在分屏模式下也是如此。当你使用分屏模式时,应用程序的窗口会发生变化。如果上面的代码没有提供您所期望的信息,那么就像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

我以前用过这些方便的方法:

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

这里我已经更新了swift 3

applicationFrame已从iOS 9弃用

在swift 3中,他们已经删除了(),他们已经改变了一些命名惯例,你可以参考这里的链接

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

func windowWidth() -> CGFloat {
    return UIScreen.main.bounds.size.width
}