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

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


目前,我使用:


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

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

在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:


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


忽然笑
浏览 1830回答 3
3回答

撒科打诨

如何在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.2let screenRect = UIScreen.main.boundslet screenWidth = screenRect.size.widthlet screenHeight = screenRect.size.height// split screen            let windowRect = self.view.window?.framelet windowWidth = windowRect?.size.widthlet windowHeight = windowRect?.size.height

幕布斯6054654

小心[UIScreen mainScreen]也包含状态栏,如果要检索应用程序的框架(不包括状态栏),则应使用+ (CGFloat) window_height   {    return [UIScreen mainScreen].applicationFrame.size.height;}+ (CGFloat) window_width   {    return [UIScreen mainScreen].applicationFrame.size.width;}

DIEA

我已经将上述一些Objective-C答案翻译成了Swift代码。每次翻译都参考原始答案。主要答案let screen = UIScreen.main.boundslet screenWidth = screen.size.widthlet screenHeight = screen.size.height简单功能答案func windowHeight() -> CGFloat {    return UIScreen.mainScreen().applicationFrame.size.height}func windowWidth() -> CGFloat {    return UIScreen.mainScreen().applicationFrame.size.width}设备方向答案var screenHeight : CGFloatlet 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}记录答案let screenWidth = UIScreen.mainScreen().bounds.size.widthlet screenHeight = UIScreen.mainScreen().bounds.size.heightprintln("width: \(screenWidth)")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS