我想为每个表格视图单元格设置计时器。目标是在时间归零后从列表中删除单元格。有自定义计时器的代码。单元格中的时间字符串不变。
private func CreateModel() {
let m1 = ModelObject(bTime: "12:13:10", eTime: "12:20:10", cTime: "12:18:10", minus: "0")
let m2 = ModelObject(bTime: "12:15:10", eTime: "12:25:10", cTime: "12:10:10", minus: "0")
let m3 = ModelObject(bTime: "12:18:10", eTime: "12:30:10", cTime: "12:10:10", minus: "0")
let m4 = ModelObject(bTime: "12:20:10", eTime: "12:35:10", cTime: "12:10:10", minus: "0")
models.append(m1)
models.append(m2)
models.append(m3)
models.append(m4)
}
func startTimer() {
listUpdateTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(reloadTable), userInfo: nil, repeats: true)
}
@objc func reloadTable() {
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TimerTableViewCell", for: indexPath) as! TimerTableViewCell
cell.delegate = self
formatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
formatter.dateFormat = "hh:mm:ss"
let currentDate = models[indexPath.row].currentTime ?? ""
let maxDate = models[indexPath.row].endTime ?? ""
let cDate = formatter.date(from: currentDate)! as NSDate
let mDate = formatter.date(from: maxDate)! as NSDate
if mDate.isGreaterThanDate(dateToCompare: cDate) {
let minus : TimeInterval = mDate.timeIntervalSince(cDate as Date)
print(minus)
var m = models[indexPath.row].minus
m = String(minus)
cell.timeLabel.text = m
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
extension ViewController : TimerTableViewCellDelegate {
func setCellTime(cell: TimerTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
models[indexPath.row].minus = cell.myTime
}
}
}
protocol TimerTableViewCellDelegate {
func setCellTime(cell:TimerTableViewCell)
}
class TimerTableViewCell: UITableViewCell {
@IBOutlet weak var timeLabel: UILabel!
var delegate : TimerTableViewCellDelegate?
var timer = Timer()
var myTime = "0"
override func awakeFromNib() {
super.awakeFromNib()
updateRow()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateRow(){
print("**************")
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.decreaseTimer), userInfo: nil, repeats: true)
}
@objc func decreaseTimer(){
if let delegate = self.delegate {
var time = Double(timeLabel.text!)!
if time > 0 {
time -= 1
}
self.myTime = String(time)
delegate.setCellTime(cell: self)
}
}
}
我正在使用协议委托更新单元格数据,在我的情况下,每个表视图重新加载调用单元计时器应该开始,但这不起作用。