Search code examples
ioscocoa-touchswiftnstimer

NSTimer isn't updating a label


So I'm trying to make a function refresh every 1 second so it updates a label, unfortunately it's not trigger for some reason. Code below with comments.

import UIKit


class ViewController: UIViewController {

    @IBOutlet var tt_CountDown: UILabel!


    var tt_currentDate = NSDate()
    var tt_objCalendar = NSCalendar.currentCalendar()


    override func viewDidLoad() {
        super.viewDidLoad()

        self.timeClassManagement()

       //The timer I'm using to call the function to repeat
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timeClassManagement"), userInfo: nil, repeats: true)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func timeClassManagement(){
        //the function that holds the code for the label below
        tt_CountDown.text = "\(String(tt_hour)):\(String(tt_minute)):\(String(tt_second))"

    }



}

Solution

  • The problem is not with he timer failing to call its action method; that is working fine. The problem is in the code you used to update the label (from our chat).

    func timeClassManagement(){ 
    var tt_objDateFormat = tt_objCalendar.components( .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: tt_currentDate) 
    
    var tt_hour = tt_objDateFormat.hour 
    var tt_minute = tt_objDateFormat.minute 
    var tt_second = tt_objDateFormat.second 
    
    tt_CountDown.text = "\(String(tt_hour)):\(String(tt_minute)):\(String(tt_second))" 
    
    }
    

    The date you're using, tt_currentDate, is the same every time the method is called. You need to pass in the current date so it will change.

    var tt_objDateFormat = tt_objCalendar.components( .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate:NSDate.date())