Status bar height in Swift

2019-03-09 06:01发布

问题:

How can I get the status bar's height programmatically in Swift?

In Objective-C, it's like this:

[UIApplication sharedApplication].statusBarFrame.size.height.

回答1:

Is there any problems with Swift 2.x:

UIApplication.sharedApplication().statusBarFrame.size.height

Swift 3 or Swift 4:

UIApplication.shared.statusBarFrame.height

Make sure UIKit is imported

import UIKit


回答2:

Swift is just a different language. The API elements are the same. Perhaps something like this:

let app = UIApplication.sharedApplication()
let height = app.statusBarFrame.size.height


回答3:

Its just like in Objective-C:

var screenStatusBarHeight: CGFloat {
    return UIApplication.sharedApplication().statusBarFrame.height
}

This is included as a standard variable in:

https://github.com/goktugyil/EZSwiftExtensions



回答4:

This is what I use:

struct Screen {
    static var width: CGFloat {
        return UIScreen.main.bounds.width
    }
    static var height: CGFloat {
        return UIScreen.main.bounds.height
    }
    static var statusBarHeight: CGFloat {
        return UIApplication.shared.statusBarFrame.size.height
    }
}

Then you can do:

Screen.statusBarHeight