Search code examples
swiftxcodeuiviewuibackgroundcolor

UIView Background Change Colors with Time


In my app, I'm wanting to a section to have an UIView to have colors that change with time. Is this possible and could I do it in an extension? Thank you in advance!!

Like:
sunrise to 10 - color
10 to 1 - color
1 to 4 - color
etc...


Solution

  • There's no magical way to achieve this. In some way, you're going to have to do the following:

    import UIKit
    
    private extension UIColor {
    
        static func viewBackground(forTime time: Date) -> UIColor {
            let earlyMorningBoundary = Calendar.current.date(bySettingHour: 6, minute: 0, second: 0, of: time)!
            let morningBoundary = Calendar.current.date(bySettingHour: 10, minute: 0, second: 0, of: time)!
            let lunchtimeBoundary = Calendar.current.date(bySettingHour: 13, minute: 0, second: 0, of: time)!
            let afternoonBoundary = Calendar.current.date(bySettingHour: 16, minute: 0, second: 0, of: time)!
            let eveningBoundary = Calendar.current.date(bySettingHour: 19, minute: 0, second: 0, of: time)!
            if time < earlyMorningBoundary {
                return UIColor.earlyMorningColor
            } else if time < morningBoundary {
                return UIColor.morningColor
            } else if time < lunchtimeBoundary {
                return UIColor.lunchtimeColor
            } else if time < afternoonBoundary {
                return UIColor.afternoonColor
            } else {
                return UIColor.eveningColor
            }
        }
    }
    
    extension UIView {
    
        func updateBackgroundForCurrentTime() {
            self.backgroundColor = .viewBackground(forTime: Date())
        }
    }
    
    extension UIColor {
    
        static var earlyMorningColor: UIColor {
            return UIColor(red: 60/255, green: 207/255, blue: 228/255, alpha: 1.0)
        }
    
        static var morningColor: UIColor {
            return UIColor(red: 5.1/255, green: 25.9/255, blue: 87.5/255, alpha: 1.0)
        }
    
        static var lunchtimeColor: UIColor {
            return UIColor(red: 0/255, green: 88.2/255, blue: 45.9/255, alpha: 1.0)
        }
    
        static var afternoonColor: UIColor {
            return UIColor(red: 0/255, green: 64.7/255, blue: 33.7/255, alpha: 1.0)
        }
    
        static var eveningColor: UIColor {
            return UIColor(red: 49/255, green: 54/255, blue: 57/255, alpha: 1.0)
        }
    }
    

    You then need to figure out when you should be calling updateBackgroundForCurrentTime to update the background color. Is it when the view is created? When the app is brought into the foreground? Will you queue a local notification to tell you to update? This will all depend on how long you think an app session is likely to last. I would start by updating the color when the app is launched or brought into the foreground and go from there.