UIView 背景随时间改变颜色



在我的应用程序中,我希望一个部分有一个UIView,以具有随时间变化的颜色。这可能吗,我可以在扩展中做到这一点吗?提前谢谢你!!

比如:
日出到10 - 颜色 10 到 1 - 颜色 1 到 4 - 颜色


等...

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

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来更新背景颜色。是在创建视图时吗?何时将应用置于前台?您是否会排队本地通知以告诉您更新?这完全取决于您认为应用会话可能持续多长时间。我会首先在应用程序启动或进入前台时更新颜色,然后从那里开始。

相关内容

  • 没有找到相关文章

最新更新