获取 iPhone 状态栏高度
我需要根据 iPhone 状态栏的高度调整一些元素的大小。我知道状态栏通常为 20 点高,但在网络共享模式下并非如此。它加倍到 40。确定其高度的正确方法是什么?我已经尝试过
[[UIApplication sharedApplication] statusBarFrame]
,但是它在横向上给我 20 x 480,这是正确的,但在纵向上它给了我 320 x 40。为什么它没有给我相反的结果(40 x 320)?
I need to resize some elements in relation to the height of the iPhone's Status Bar. I know that the status bar is usually 20 points high but this isn't the case when it's in tethering mode. It gets doubled to 40. What is the proper way to determine it's height? I've tried
[[UIApplication sharedApplication] statusBarFrame]
but it gives me 20 x 480 in landscape which is correct but then it gives me 320 x 40 in portrait. Why isn't it giving me the opposite of that (40 x 320)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
statusBarFrame 返回屏幕坐标中的框架。我相信获取视图坐标中对应的内容的正确方法是执行以下操作:
现在,在大多数情况下,窗口使用与屏幕相同的坐标,因此
[UIWindow ConvertRect:fromWindow:]
不会不会改变任何东西,但在它们可能不同的情况下,这个方法应该做正确的事情。The statusBarFrame returns the frame in screen coordinates. I believe the correct way to get what this corresponds to in view coordinates is to do the following:
Now in most cases the window uses the same coordinates as the screen, so
[UIWindow convertRect:fromWindow:]
doesn't change anything, but in the case that they might be different this method should do the right thing.你是这样做的吗:
Did you do it like this:
此方法适用于肖像和肖像。横向。
This method works for portrait & landscape orientation.
编辑
iOS 11 确定视图内容顶部放置位置的方法是 UIView 的
safeAreaLayoutGuide
请参阅 UIView 文档。已弃用的答案
如果您的目标是 iOS 7+,UIViewController 的文档建议 viewController 的
topLayoutGuide
属性为您提供状态栏的底部或导航栏的底部(如果它也可见)。这可能有用,而且肯定比许多以前的解决方案更省事。EDIT
The iOS 11 way to work out where to put the top of your view content is UIView's
safeAreaLayoutGuide
See UIView Documentation.DEPRECATED ANSWER
If you're targeting iOS 7+, The documentation for UIViewController advises that the viewController's
topLayoutGuide
property gives you the bottom of the status bar, or the bottom of the navigation bar, if it's also visible. That may be of use, and is certainly less hack than many of the previous solutions.您可以测试两个值中较小的一个,这将是真实高度。
You could test which is the lesser of the two values, that will be the real height.
Swift 2:
Swift 3 或 Swift 4:
建议: 不要忘记注入
UIApplication.shared
do不仅仅是在代码中使用单例。Swift 2:
Swift 3 or Swift 4:
Advice: Don't forget to inject the
UIApplication.shared
do not just use the singleton in your code.如果有人需要的话,这是 Swift 版本:
这作为标准变量包含在:
https://github.com/ goktugyil/EZSwiftExtensions
免责声明:它是我的存储库
Here is the Swift version if anyone needs it:
This is included as a standard variable in:
https://github.com/goktugyil/EZSwiftExtensions
Disclaimer: Its my repo