lundi 6 juillet 2020

create if statement based on time

I want my swift code to follow a if statement based on a certain time. My timer is in military time right now. So I want to do something like if the hour in time is 01:00 to 01:59. Then the view background color should turn blue. So I am just trying to control the hour time in the time style.

import UIKit

class ViewController: UIViewController {
    var box = UILabel()

    @objc func tick() {
        box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
    }
    
    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

        box.text = "\(dateFormatter.string(from: currentDateTime))"      
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        box.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
        box.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(box)
        box.backgroundColor = .red   
        NSLayoutConstraint.activate([
            box.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5),
            box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
            box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            box.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }

}

Aucun commentaire:

Enregistrer un commentaire