Home > Software design >  Change the color based on user's current time in SwiftUI
Change the color based on user's current time in SwiftUI

Time:07-01

I have a weather app where I want to implement a dynamic color (gradient) change based on a time of the day i.e. when it's morning, the background is light blue, when it's night – it's purple, etc.

Basically, I understand there should be a global function but I don't really know how to tap into a user's actual time and write smth like:

switch time {

case "05:00" : 
return Color.blue

case "10:00" : 
return Color.yellow
...
...
...
}

CodePudding user response:

Here's how to get the current hour and minute:

let hour = Calendar.current.component(.hour, from: Date())
let minute = Calendar.current.component(.minute, from: Date())

And, in your case:

let hour = Calendar.current.component(.hour, from: Date())

switch hour {

case 5:
return Color.blue

case 10:
return Color.yellow
...
...
...
}
  • Related