belab belab - 3 months ago 41
Swift Question

swift changing background color based on day time

Heyy, I'm a really-newbie in ios programming. In my app, I would like to change background color based on the time of day.
This is the task:


In the evening, the background should be a dark color. Otherwise, the
background should be a light color. You will need to override
viewWillAppear(_:)


Any ideas? I guess that it's pretty simple, but please, understand my level.
Thanks.

Answer

In viewWillAppear:

//Get current time
let components = NSCalendar.currentCalendar().components(.CalendarUnitHour | .CalendarUnitMinute, fromDate:  NSDate())
let currentHour = components.hour 

//Set background color accordingly
if currentHour >= 18 {
    self.view.backgroundColor = //a dark color
} else {
    self.view.backgroundColor = //a light color
}
Comments