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

How to get the screen width and height in iOS?(如何在 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 中获取屏幕宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)