Search code examples
iosswiftstatusbar

changing status bar color depending on time


Not sure if it is possible, but is there a way to change the status bar color depending on the time? I was fiddling with this code:

import UIKit

class testTimeController: UIViewController{

func lightstatusbar() {
var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
 }
}

  func darkstatusbar() {
var preferredStatusBarStyle: UIStatusBarStyle {
    return .default
}
}

override func viewDidLoad() {
    super.viewDidLoad()
let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

 switch hour{
    case 1..<6: lightstatusbar()
        break
    case 7..<18: darkstatusbar()
        break
    case 19..<24: lightstatusbar()
        break
    default: darkstatusbar()
    }
}

Solution

  • The other answers don't work for me, so here is my working solution, regarding to this answer:

    Step 1 Add following to your info.plist:

    View controller-based status bar appearance with Boolean value NO

    enter image description here

    Step 2 Add this to application(_:didFinishLaunchingWithOptions:) in AppDelegate.swift:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
      let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)
    
      switch hour {
      case 1..<6:
        UIApplication.shared.statusBarStyle = .lightContent
      case 7..<18:
        UIApplication.shared.statusBarStyle = .default
      case 19..<24:
        UIApplication.shared.statusBarStyle = .lightContent
      default:
        UIApplication.shared.statusBarStyle = .default
      }
    
      return true
    }