Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Status bar height in Swift

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

In Objective-C, it's like this:

[UIApplication sharedApplication].statusBarFrame.size.height.
like image 532
Oleshko Avatar asked Sep 22 '14 12:09

Oleshko


People also ask

What is the height of status bar in Android?

Official height is 24dp , as is stated officially by Google on Android Design webpage.

How do I get the status bar height in react native?

currentHeight : import {StatusBar} from 'react-native'; console. log('statusBarHeight: ', StatusBar. currentHeight);


4 Answers

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

In iOS 13, you will get a deprecated warning"

'statusBarFrame' was deprecated in iOS 13.0: Use the statusBarManager property of the window scene instead.

To fix this:

let height = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
like image 187
Kirsteins Avatar answered Oct 16 '22 11:10

Kirsteins


Updated Answer Supporting iOS 13+ and older iOS Versions for Swift 5

 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
}

Happy Coding!

like image 28
Md. Ibrahim Hassan Avatar answered Oct 16 '22 10:10

Md. Ibrahim Hassan


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 {
  let viewController = UIApplication.shared.windows.first!.rootViewController
  return viewController!.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
 }

}

Then you can do:

Screen.statusBarHeight
like image 8
Bobby Avatar answered Oct 16 '22 11:10

Bobby


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
like image 7
vcsjones Avatar answered Oct 16 '22 12:10

vcsjones