ch1maera
ch1maera

Reputation: 1447

Change Status Bar from Light to Dark

In my code, I currently have a variable dayTime that is true if it's light outside and false if it's night. Accordingly, my code features a white scheme for day time and a dark scheme for nighttime. I need my status bar to be black if dayTime is true and white if dayTime is false. Currently, I set override var preferredStatusBarStyle() to return .lightContent but I don't know how to call setNeedsStatusBarAppearanceUpdate() to change the status bar to black.

EDIT: Added Code from View Controller

class BasicViewController: UIViewController {

    var dayTime = true

    override func viewDidLoad() {
        super.viewDidLoad()

        // gets current time to see if it is time to toggle night mode
        let date = NSDate()
        let calendar = Calendar.current
        let components = calendar.dateComponents([.hour, .minute], from: date as Date)
        let hour = components.hour

        if(dayTime) {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

Upvotes: 2

Views: 439

Answers (1)

Tristan Beaton
Tristan Beaton

Reputation: 1762

This is how I got it to work. Although I had it do an async task so I could see it change after the task had completed.

class ViewController: UIViewController {

    var dayTime = true

    override func viewDidLoad() {
        super.viewDidLoad()

        dayTime = false

        self.setNeedsStatusBarAppearanceUpdate()
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {

        if daytime {

            return .default
        }

        return .lightContent
    }
}

Upvotes: 2

Related Questions