ios - Tableview Swift 中的多个计时器

标签 ios swift timer

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

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

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

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

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

如有任何帮助,我们将不胜感激。

编辑:

Dequeue issue

计时器应该以递增的顺序显示时间,因为每一行(连同计时器)都是从上到下创建的,这意味着第一行的时间比下一行的时间少。看起来出队时有些东西搞砸了。

Here是我用于上面截图的要点

最佳答案

下面是如何在每个 UITableViewCell 中处理 timers

创建自定义 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,它将更新 UI 中的 counter 值。
  2. handler - 当cell被移出屏幕
  3. timer - 在 cell 中安排 timer timeinterval = 1
  4. counter - 每个 cell
  5. 的当前 counter

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 - 跟踪 tableView 中每个 cellcounter 值。
  2. tableView(_:cellForRowAt:) 中,使用 handler 更新每个 cellcounter我们之前在 CustomCell 中创建。

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

相关文章:

ios - 对数组中具有相同属性值的元素进行分组

java - 两个不同 JPanel 上的 PaintComponent 坐标

c++ - 你如何在 C++ 中的特定时间每天调用一次函数?

ios - 台风 - 额外的协作组件激活

ios - 如何在 Firestore 中删除 int、double、float 的可选值?

ios - iOS app 的截图方法是什么?

ios - 如何知道 UITableView 何时完成 reloadData?

objective-c - 如何使用 MKNetworkKit 的示例项目

IOS 使用 SDWebImage 从 URL 加载图像

c# - WPF中GUI的定时刷新