我的整个应用程序(所有视图控制器)都有背景,我想根据一天中的时间更改它。如果时间是早上6点,我想显示"背景一"如果超过晚上9点,"背景二"应该显示。我正在考虑使用NSTimer检查当前时间是否超过定义的时间。为了改变背景,我考虑使用Extension for UIViewController。如果有更好的解决方案,我们将不胜感激分享。
答案 0 :(得分:4)
你可以这样做:
代码示例,签出解释说明:
import UIKit
extension Date {
var hour: Int { return Calendar.current.component(.hour, from: self) } // get hour only from Date
}
class ViewController: UIViewController {
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Declare an observer for UIApplicationDidBecomeActive
NotificationCenter.default.addObserver(self, selector: #selector(scheduleTimer), name: .UIApplicationDidBecomeActive, object: nil)
// change the background each time the view is opened
changeBackground()
}
func scheduleTimer() {
// schedule the timer
timer = Timer(fireAt: Calendar.current.nextDate(after: Date(), matching: DateComponents(hour: 6..<21 ~= Date().hour ? 21 : 6), matchingPolicy: .nextTime)!, interval: 0, target: self, selector: #selector(changeBackground), userInfo: nil, repeats: false)
print(timer.fireDate)
RunLoop.main.add(timer, forMode: .commonModes)
print("new background chenge scheduled at:", timer.fireDate.description(with: .current))
}
func changeBackground(){
// check if day or night shift
self.view.backgroundColor = 6..<21 ~= Date().hour ? .yellow : .black
// schedule the timer
scheduleTimer()
}
}