Reputation: 13
let homepageDay = UIImage(cgImage: "Homepage Day" as! CGImage)
let homepageNight = UIImage(cgImage: "Homepage Night" as! CGImage)
let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)
switch hour
{
// hours 1 to 6
case 1...6: homepageDay. = UIImage
//self.backgroundImage = homepageNight
break
// hours 7 to 18
Want to change background image depending on time of day
Upvotes: 1
Views: 519
Reputation: 3086
get hours of current date in a variable like:
let hour = Calendar.current.component(.hour, from: Date())
Now pass this to your switch statement and change the image.
Your Swift Statement will be like this (Change images as per your need):
switch hour {
case 1...6:
yourImageView.image = homepageNight
case 7...18:
yourImageView.image = homepageNight
default:
yourImageView.image = homepageNight
}
If you have any doubts please comment.
Happy to help!
Upvotes: 1
Reputation: 21
If you only need to get the current hour and know if its AM or PM, you can use something like this:
let formatter = DateFormatter()
formatter.dateFormat = "hh a" // "a" prints "pm" or "am"
let hourString = formatter.string(from: Date()) // "12 AM"
So, after this you only need to apply your correct image bay the hour getting the string value.
Upvotes: 0