简体   繁体   English

如何适配ios13状态栏?

[英]How to adapt ios13 statusbar?

When I run my project on ios13 xcode11 beta.当我在 ios13 xcode11 beta 上运行我的项目时。

[UIApplication sharedApplication].statusBarFrame.size.height

the code returns 0.代码返回 0。

what should I do to adapt it to ios13 ?我应该怎么做才能使其适应 ios13?

Use UIStatusBarManager to get the statusBar height in iOS13: 使用UIStatusBarManager获取iOS13中的statusBar高度:

UIStatusBarManager *manager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;

CGFloat height = manager.statusBarFrame.size.height;

SceneDelegate.swift file SceneDelegate.swift文件

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    guard let windowScene = (scene as? UIWindowScene) else { return }
    if let statusBarFrame = windowScene.statusBarManager?.statusBarFrame {
        print(statusBarFrame)
    }
}

As Peter noted on Tamarous's answer, the keyWindow property is deprecated, however on the assumption you're using a single window you can alternatively use:正如彼得Tamarous 的回答中指出的那样,不推荐使用keyWindow属性,但是假设您使用的是单个窗口,您也可以使用:

CGSize statusBarSize = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager.statusBarFrame.size

If you needed to access the nth window, you could do so in a similar manner:如果您需要访问第n 个窗口,您可以采用类似的方式:

NSInteger i = 0;
CGSize statusBarSize = [UIApplication sharedApplication].windows[i].windowScene.statusBarManager.statusBarFrame.size;

Solution:解决方案:

let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
lazy var statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0

Explanation :解释 :

You can't use window in a let because it doesn't exist when that property is created because it belongs to self.您不能在let使用window ,因为在创建该属性时它不存在,因为它属于 self. So at init , self isn't complete yet.所以在initself还没有完成。 But if you use a lazy var , then self and its property window will be ready by the time you need it.但是,如果您使用lazy var ,则self及其属性window将在您需要时准备就绪。

Or another solution use singleton :或另一种解决方案使用singleton

struct AppConstants {
    static let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
    static let statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM