Я создаю таймер обратного отсчета в TableViewCell. и это работает отлично. но когда я прокручиваю вниз, а затем прокручиваю вверх, таймер ячейки сбрасывается с начальным значением. Я не понимаю, что я здесь делаю, поэтому он не будет обновляться или сбрасываться с начальным значением. Пожалуйста, помогите мне любой приятель получил.
Мой код класса TableViewCell:
class DealOfferCell: UITableViewCell {
@IBOutlet weak var CellCardView: UIView!
@IBOutlet weak var CellBurgerKingImage: UIImageView!
@IBOutlet weak var CellImageView: UIImageView!
@IBOutlet weak var CellGetOffLabel: UILabel!
@IBOutlet weak var CellOnAWhopperLabel: UILabel!
@IBOutlet weak var CellDealEndsOnLabel: UILabel!
@IBOutlet weak var CellDealItemNameLabel: UILabel!
@IBOutlet weak var DealLeftButton: UIButton!
private var timer: Timer?
fileprivate var timeCounter: Double = 0
var expiryTimeInterval: TimeInterval? {
didSet {
if timer == nil
{
startTimer()
RunLoop.current.add(timer!, forMode: .commonModes)
}
}
}
private func startTimer() {
if let interval = expiryTimeInterval {
timeCounter = interval
if #available(iOS 10.0, *) {
timer = Timer(timeInterval: 1.0,
repeats: true,
block: { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.onComplete()
})
} else {
timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(onComplete),
userInfo: nil,
repeats: true)
}
}
}
@objc func onComplete() {
guard timeCounter >= 0 else {
// btnGoForTest.isUserInteractionEnabled = false
CellDealEndsOnLabel.text = "Time ended."
timer?.invalidate()
timer = nil
return
}
// btnGoForTest.isUserInteractionEnabled = true
let hours = Int(timeCounter) / 3600
let minutes = Int(timeCounter) / 60 % 60
let seconds = Int(timeCounter) % 60
CellDealEndsOnLabel.text = "DEAL ENDS ON " + String(format:"%02i:%02i:%02i", hours, minutes, seconds)
timeCounter -= 1
print("\(timeCounter)")
}
override func prepareForReuse() {
super.prepareForReuse()
timer?.invalidate()
timer = nil
}
}
И код внутри CellForIndexPath:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = DealsOffersTableView.dequeueReusableCell(withIdentifier: "MapCell", for: indexPath) as! MapCell
let getTime1 : Double = Double(500)
cell.expiryTimeInterval = getTime1
}