Search code examples
iosswiftstatusbar

How to set black status bar with a background image in iPhone X?


App has an yellow image as a background, and status bar is set hidden, it works well on other devices except iPhone X.

The status bar sticks on white text color.

enter image description here

I tried to add the following code, still failed:

override var preferredStatusBarStyle: UIStatusBarStyle{
  return .default      
}

Any other suggestion?

Thanks.


Solution

  • Method 1:

    You have to add this value to plist: "View controller-based status bar appearance" and set it to "NO".

    After that add this in AppDelegate

       var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            window = UIWindow(frame: UIScreen.main.bounds)
            if #available(iOS 11.0, *) {
                if (window?.safeAreaInsets.top)! > CGFloat(0.0) || window?.safeAreaInsets != .zero {
                    print("iPhone X")
                    application.isStatusBarHidden = true
                    //or UIApplication.shared.isStatusBarHidden = true
                }
                else {
                    print("Not iPhone X")
                    application.isStatusBarHidden = true
                }
            }
            return true
        }
    

    Method 2: "View controller-based status bar appearance" and set it to "YES". Which is by default.

    As in iOS11+ setStatusBarHidden & isStatusBarHidden are deprecated, [prefersStatusBarHidden][2] is available from iOS7+, We can make status bar visibility settings over ViewController as-

    struct StatusBarInfo {
        static var isToHiddenStatus = false
      }
        var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            if #available(iOS 11.0, *) {
                if (window?.safeAreaInsets.top)! > CGFloat(0.0) || window?.safeAreaInsets != .zero {
                    print("iPhone X")
                    StatusBarInfo.isToHiddenStatus = true
                }
                else {
                    StatusBarInfo.isToHiddenStatus = true
                    print("Not iPhone X")
                }
            }
            return true
        }
    

    In ViewController.Swift

    override var prefersStatusBarHidden: Bool {
            return StatusBarInfo.isToHiddenStatus
        }