Swift - Update/Refresh Label that Displays Time

后端 未结 2 1821
花落未央
花落未央 2021-01-03 08:05

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 a

2条回答
  •  余生分开走
    2021-01-03 08:14

    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
        }
    
    }
    

提交回复
热议问题