3

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()
    }
}

3 Answers3

2

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
}
Community
  • 1
  • 1
ronatory
  • 6,311
  • 3
  • 24
  • 41
0

Yes, but instead just implement and ovveride

override var preferredStatusBarStyle: UIStatusBarStyle {
    let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

     switch hour{
    case 1..<6: .lightContent
        break
    case 7..<18: .darkContent
        break
    case 19..<24: .lightContent
        break
    default: .darkContent
}

Dont put the var inside another method that wont do anything.

Sean Lintern
  • 2,961
  • 17
  • 25
0

I used @SeanLintern88 approach, just added "return"

override var preferredStatusBarStyle: UIStatusBarStyle {
    let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

    switch hour{
    case 1..<6: return.lightContent

    case 7..<18: return.default

    case 19..<24: return.lightContent

    default: return.default
    }
}
  • this really works for you? What if you just set `let hour = 1`, to test if your status bar is `.lightContent`? Just tested the code and for me it's not working – ronatory Dec 21 '16 at 17:33