I want my codes background uiviewcontroller background to change depending on the hour. If the code is in the first 60 minutes of the day the background color works. However when the time goes to the second hour the view color does not change from gray to pink. I want when the hour changes the background color to be change. Just worry about the first 2 hours of the day as listed below. The code is in military time. Func is being called from viewdidappear.
import UIKit
class ViewController: UIViewController {
var timer = Timer()
var currentDateTime = Date()
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm" // or "hh:mm a" if you need to have am or pm symbols
return formatter
}()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
dateFormatter.timeStyle = .medium
halsey()
}
var count = 0
fileprivate func halsey() {
let minutesNow = getMinutesFromDate(date: Date())
if minutesNow >= 0 && minutesNow < 60 {
//12
if count == 0{
box.backgroundColor = .gray
count += 1
}
}
if minutesNow >= 60 && minutesNow < 120 {
//1
if count == 1 {
view.backgroundColor = .systemPink
count += 1
}
}
}
@objc func tick() {
}
func getMinutesFromDate(date: Date) -> Int {
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
let minutes = ((dateComponents.hour ?? 0) * 60) + (dateComponents.minute ?? 0)
return minutes
}
}
You need to remove
and any code related to it , as if the app is opened at second hour and
count = 0at that time then this code will not hilt