0
我在所有應用程序(所有視圖控制器)中都有背景,我想根據一天中的時間更改背景。如果時間是上午6點,我想顯示「背景一」,如果超過9點PM,應顯示「背景二」。我正在考慮使用NSTimer檢查當前時間是否超過定義的時間。爲了改變背景,我正在考慮使用Extension for UIViewController。如果有更好的解決方案,將不勝感激。每天不同時間更改背景 - iOS
我在所有應用程序(所有視圖控制器)中都有背景,我想根據一天中的時間更改背景。如果時間是上午6點,我想顯示「背景一」,如果超過9點PM,應顯示「背景二」。我正在考慮使用NSTimer檢查當前時間是否超過定義的時間。爲了改變背景,我正在考慮使用Extension for UIViewController。如果有更好的解決方案,將不勝感激。每天不同時間更改背景 - iOS
你可以這樣說:
代碼示例,結帳說明意見:
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()
}
}
優雅而不錯 - > +1 –
我如何使Usage部分一次性事件。我想做一次,而不是在每個視圖控制器中都做。 –
@HosAp,您可以在AppDelete函數的'func applicationDidBecomeActive(_ application:UIApplication)'函數中使用「用法」代碼,每次應用程序變爲活動狀態時調用該函數。 –