ios - UITableViewCell 中的多个计时器(Swift)

标签 ios swift uitableview nstimer

我有在不同时刻创建的 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。当然,您需要添加适当的检查来处理它是可选的。

您必须做的最后一项更改是更改 timertimeblinkStatus,通过将它们移动到类。

关于ios - UITableViewCell 中的多个计时器(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350895/

相关文章:

json - 在 Swift 字典中使用键值映射索引位置

ios - 如何快速分离变量并将键设置为 true ?

iphone - 当UISearchbar获得焦点时,UITableView如何 "dim"实际表格?

ios - UISearchDisplayController 的具体用途是什么?

ios - 如何使 UICollectionViewCell 的动态宽度

ios - App Store不接受Ant Media Server的iOS框架吗?

ios - 将相机移动到底部 GMSMapView IOS

ios - 位码仍然可以在 Xcode 9.2 上禁用吗?

ios - TableView 在索引路径问题上重新加载行

ios - tableView的顶部有一些空白区域