我有在不同时刻创建的 UITableViewcells
,我希望它们中的每一个都有一个独立的计时器,当使用 reloadData()添加对象时触发
这是我目前所做的
import UIKit
var timer = Timer()
var blinkStatus:Bool! = false
var time = 300
class LiveViewCell: UITableViewCell {
let str = String(format:"%02d:%02d", (time / 60), (time % 100))
func processTimer() {
if time > 0 {
time -= 1
timeRemainingLbl.text = String(time)
} else if time == 0 {
timer.invalidate()
timeRemainingLbl.text = "Due!"
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(LiveViewCell.blinkTimer), userInfo: nil, repeats: true)
}
}
func blinkTimer() {
if blinkStatus == false {
timeRemainingLbl.textColor = UIColor(red:1.00, green:0.00, blue:0.00, alpha:1.0)
blinkStatus = true
} else if blinkStatus == true {
timeRemainingLbl.textColor = UIColor.clear
blinkStatus = false
}
}
@IBOutlet weak var tableNumberLeftLabel: UILabel!
@IBOutlet weak var guestNumbersLabel: UILabel!
@IBOutlet weak var timeInTableLabel: UILabel!
@IBOutlet weak var tableNumberLbl: UILabel!
@IBOutlet weak var timeRemainingLbl: UILabel!
var table: Table!
func configureLiveCell(_ NT: Table) {
layer.cornerRadius = 20
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(LiveViewCell.processTimer), userInfo: nil, repeats: true)
tableNumberLbl.text = "T" + String(NT.number)
timeRemainingLbl.text = String(time)
}
}
每当我创建一个新单元时调用 configureLiveCell
时就会出现问题。计时器似乎在加速,我希望每个计时器都是独立的。
最佳答案
覆盖 prepareForReuse
方法。
override func prepareForReuse() {
super.prepareForReuse()
timer.invalidate()
}
这将在单元格返回以供另一行使用之前调用。通过在此处使计时器无效,您的 configureLiveCell
不会创建另一个计时器。
顺便说一句 - 你还应该添加一个 deinit
方法并在那里也使计时器无效。
您还可以将 timer
属性设为可选,并在使它无效后将其设置为 nil
。当然,您需要添加适当的检查来处理它是可选的。
您必须做的最后一项更改是更改 timer
、time
和 blinkStatus
,通过将它们移动到类。
关于ios - UITableViewCell 中的多个计时器(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350895/