UIView背景随时间更改颜色

时间:2018-10-21 04:46:46

标签: swift xcode uiview uibackgroundcolor

在我的应用中,我想让一个部分具有一个UIView来具有随时间变化的颜色。这可能吗,我可以扩展吗?预先谢谢你!

赞:
日出至10-颜色
10比1-颜色
1至4-颜色
等等...

1 个答案:

答案 0 :(得分:0)

没有神奇的方法可以实现这一目标。在某种程度上,您将必须执行以下操作:

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)
    }
}

然后,您需要弄清楚何时致电updateBackgroundForCurrentTime来更新背景色。创建视图时是吗?当应用程序出现在前台时?您会在本地通知队列中告诉您进行更新吗?这完全取决于您认为应用会话可能持续多长时间。我将首先在应用启动或进入前台并从那里转到那里时更新颜色。