Tableview Swift中的多个计时器

时间:2019-06-05 15:22:47

标签: ios swift timer

我正在尝试为用户单击添加按钮时手动添加的每一行设置计时器。

开始时间设置为100个单位(对于该问题并不重要),并且应该倒计时。

添加新行时,它将启动自己的计时器,并在新行上显示值。

我试图在每个单元格中都有一个计时器,但这在出队时会产生问题,因此我创建了一个计时器数组来为每个单元格保存相应的计时器。我现在面临的问题是如何每秒(计时器间隔)更新单元格值

MultipleTimersTableView_Gist是我到目前为止编写的代码的链接。我曾想过使用委托来更新单元格,但不确定采用最佳方法。

任何帮助将不胜感激。

编辑:

Dequeue issue

计时器应该以递增的顺序显示时间,因为创建的每一行(以及计时器)都是自上而下的,这意味着第一行将比下一行少。看起来像是在出局时弄乱了东西。

Here是我用于上述屏幕截图的要旨

2 个答案:

答案 0 :(得分:1)

以下是您在每个timers中处理UITableViewCell的方式。

创建自定义UITableViewCell

class CustomCell: UITableViewCell {
    //MARK: Outlets
    @IBOutlet weak var label: UILabel!

    //MARK: Internal Properties
    var handler: ((Int)->())?

    //MARK: Private Properties
    private var timer: Timer?
    private var counter = 100 {
        didSet {
            DispatchQueue.main.async {
                self.label.text = "\(self.counter)"
                self.handler?(self.counter)
            }
        }
    }

    //MARK: Internal Methods
    func configure(with counter: Int) {
        self.counter = counter
        self.setTimer()
    }

    //MARK: Private Methods
    private func setTimer() {
        self.timer?.invalidate()
        self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {[weak self] (timer) in
            if let counter = self?.counter, counter > 0 {
                self?.counter -= 1
            } else {
                timer.invalidate()
            }
        })
    }
}

在上面的代码中,

  1. 我创建了一个label,它将更新counter中的UI值。
  2. handler-当counter从屏幕移出时,它将更新的ViewController值存储在某个地方(在cell中,进一步说明)
  3. timer-将timer中的celltimeinterval = 1一起安排
  4. counter-每个counter的当前cell

ViewController中,

class VC: UIViewController, UITableViewDataSource {
    let numberOfCells = 20
    var timerArr = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.timerArr = [Int](repeating: 100, count: numberOfCells)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.numberOfCells
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
        cell.configure(with: self.timerArr[indexPath.row])
        cell.handler = {[weak self] (counter) in
            self?.timerArr[indexPath.row] = counter
        }
        return cell
    }
}

在上面的代码中,

  1. timerArr-跟踪counter中每个cell的{​​{1}}值。
  2. tableView中,使用我们先前在tableView(_:cellForRowAt:)中创建的counter更新每个cell的{​​{1}}。

答案 1 :(得分:0)

我将对所有单元使用一个计时器。创建对象并将其添加到数据源时,记录dateAdded = Date(),然后在计时器启动时重建单元格时,从dateAdded字段获取每个单元格的秒数,并更新cellForRowAtIndex中的单元格。