如何在 iOS 中获取屏幕宽度和高度? [英] How to get the screen width and height in iOS?

查看:30
本文介绍了如何在 iOS 中获取屏幕宽度和高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can one get the dimensions of the screen in iOS?

目前,我使用:

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

viewWillAppear:willAnimateRotationToInterfaceOrientation:duration:

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

The first time I get the entire screen size. The second time i get the screen minus the nav bar.

推荐答案

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

How can one get the dimensions of the screen in iOS?

您发布的代码的问题在于您指望视图大小与屏幕大小相匹配,但正如您所见,情况并非总是如此.如果你需要屏幕尺寸,你应该看看代表屏幕本身的对象,像这样:

The problem with the code that you posted is that you're counting on the view size to match that of the screen, and as you've seen that's not always the case. If you need the screen size, you should look at the object that represents the screen itself, like this:

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

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

Update for split view: In comments, Dmitry asked:

如何获取拆分视图中的屏幕尺寸?

How can I get the size of the screen in the split view?

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

The code given above reports the size of the screen, even in split screen mode. When you use split screen mode, your app's window changes. If the code above doesn't give you the information you expect, then like the OP, you're looking at the wrong object. In this case, though, you should look at the window instead of the screen, like this:

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

这篇关于如何在 iOS 中获取屏幕宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆