Reputation: 275
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))"
}
}
Upvotes: 0
Views: 622
Reputation: 104082
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())
Upvotes: 3
Reputation: 2045
Just pass a string of the function name to the NSTimer
init. Selectors are an ObjC construct, and methods that accept selectors can be given strings in Swift.
First timer
should be a property. It'll be gone by the time viewDidLoad
ends.
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timeClassManagement", userInfo: nil, repeats: true)
More detail is offered in this answer to a similar question: See the answer here: https://stackoverflow.com/a/24007718/3879
Upvotes: 1