Answers:
Swift 2.x是否有任何问题:
UIApplication.sharedApplication().statusBarFrame.size.height
Swift 3或Swift 4:
UIApplication.shared.statusBarFrame.height
确保UIKit
已导入
import UIKit
在iOS 13中,您将收到不赞成使用的警告”
在iOS 13.0中不建议使用“ statusBarFrame”:而是使用窗口场景的statusBarManager属性。
要解决此问题:
let height = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
size
在Swift 3中省略:UIApplication.shared.statusBarFrame.height
足够了。
view.window?
为UIApplication.shared.keyWindow?
更新的Answer支持Swift 13的iOS 13+和更旧的iOS版本
func getStatusBarHeight() -> CGFloat {
var statusBarHeight: CGFloat = 0
if #available(iOS 13.0, *) {
let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
statusBarHeight = UIApplication.shared.statusBarFrame.height
}
return statusBarHeight
}
编码愉快!
就像在Objective-C中一样:
var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
}
它作为标准变量包括在:
重做易卜拉欣的答案:
extension UIApplication {
static var statusBarHeight: CGFloat {
var statusBarHeight: CGFloat = 0
if #available(iOS 13.0, *) {
let window = shared.windows.filter { $0.isKeyWindow }.first
statusBarHeight = window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
statusBarHeight = shared.statusBarFrame.height
}
return statusBarHeight
}
}
在我的swiftUI项目中,此方法有效。
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
if let statusBarHeight = window.windowScene?.statusBarManager?.statusBarFrame.height {
SceneDelegateDataGetter.shared.height = statusBarHeight
}
window.rootViewController = HostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
class SceneDelegateDataGetter {
static let shared = SceneDelegateDataGetter()
public fileprivate(set) var height: CGFloat = 0
}
使用时
SceneDelegateDataGetter.shared.height
UIApplication.shared.statusBarFrame.size.height