简体   繁体   中英

How to adapt ios13 statusbar?

When I run my project on ios13 xcode11 beta.

[UIApplication sharedApplication].statusBarFrame.size.height

the code returns 0.

what should I do to adapt it to ios13 ?

Use UIStatusBarManager to get the statusBar height in iOS13:

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

CGFloat height = manager.statusBarFrame.size.height;

SceneDelegate.swift file

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:

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:

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. So at init , self isn't complete yet. But if you use a lazy var , then self and its property window will be ready by the time you need it.

Or another solution use singleton :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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