How to get the screen width and height in iOS?(如何在 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 中获取屏幕宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 iOS 中获取屏幕宽度和高度?
基础教程推荐
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
