Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Update/Refresh Label that Displays Time

Tags:

ios

swift

swift3

I have a label which displays the current time in 12-hour format.

But, it does not update/refresh the time every time the minute/hour changes.

I need it to automatically change the label to the current time when the time changes.

like image 858
reecefox Avatar asked Dec 08 '22 19:12

reecefox


2 Answers

Swift 3 Solution

class ViewController {

    @IBOutlet weak var timeLabel: UILabel!
    var timer: Timer?

    let formatter: DateFormatter = {
        let tmpFormatter = DateFormatter()
        tmpFormatter.dateFormat = "hh:mm a"
        return tmpFormatter
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.getTimeOfDate), userInfo: nil, repeats: true)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        timer?.invalidate()
    }

    func getTimeOfDate() {
        var curDate = Date()

        timeLabel.text = formatter.string(from: curDate)
    }

}
like image 79
Ganesh Kumar Avatar answered Dec 10 '22 08:12

Ganesh Kumar


Replace following code with your ViewController code then connect IBOutlet to showTimeLbl

class ViewController: UIViewController {

    @IBOutlet weak var showTimeLbl: UILabel!
    var timeCount:Int = 0
    var timer:Timer!

    override func viewDidLoad() {
        super.viewDidLoad()

        if(timer != nil)
        {
            timer.invalidate()
        }
        timer = Timer(timeInterval: 1.0, target: self, selector: #selector(ViewController.timerDidFire), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

    }

    func timerDidFire()
    {
        timeCount += 1

        showTimeLbl.text = NSString(format: "%02d:%02d:%02d", timeCount/3600,(timeCount/60)%60,timeCount%60) as String
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        timer?.invalidate()
        timer = nil
    }

}
like image 44
Jugal K Balara Avatar answered Dec 10 '22 09:12

Jugal K Balara