I'm creating a timer in tableview cell's class and updating a label each second using the timer. But the label is getting updating multiple times each second for some cells while it is being updated at a different rate for other cells. I think the resusability of the cell might be causing the problem.
I'm creating the timer object as an instance variable:
var timer: Timer!
and calling:
runTimer(). //called in awakefromnib
while the runtimer method is:
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}
func updateTimer() {
seconds -= 1
timerLabel.text = timeString(time: seconds)
}
What is the correct way to create a timer which update UILabel
each second for each cell depending on some login in cell?
EDIT: This if my cellforrowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Doubts Cell", for: indexPath) as! DoubtsTableViewCell
cell.postedQuestionAndAnswer = postedQuestionsArray[indexPath.row]
if cell.timer != nil {
cell.timer.invalidate()
}
cell.runTimer()
return cell
}
and this is my required cell's class code:
var postedQuestionAndAnswer: PostedQuestionAndAnswer! {
didSet {
configureTableViewData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
func configureTableViewData() {
//.....other code
seconds = getTimeRemaining(queryPostedTime: Double(postedQuestionAndAnswer.question!.createdAt), queryPostedDate: Double(postedQuestionAndAnswer.question!.createdAt))
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}
func updateTimer() {
seconds -= 1
timerLabel.text = timeString(time: seconds) //timestring returns desired formatted string
}