我正在尝试为每一行设置计时器,当用户单击添加按钮时手动添加该计时器。
开始时间设置为 100 个单位(对问题不重要),它应该倒计时。
添加新行时,它会启动自己的计时器并在新行上显示值。
我尝试在每个单元格中设置计时器,但这会在出队时产生问题,因此我创建了一个计时器数组来为每个单元格保存相应的计时器。我现在面临的问题是如何每秒更新单元格值(定时器间隔)
MultipleTimersTableView_Gist是我到目前为止编写的代码的链接。我考虑过使用委托(delegate)来更新单元格,但不确定最佳方法。
如有任何帮助,我们将不胜感激。
编辑:
计时器应该以递增的顺序显示时间,因为每一行(连同计时器)都是从上到下创建的,这意味着第一行的时间比下一行的时间少。看起来出队时有些东西搞砸了。
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()
}
})
}
}
在上面的代码中,
- 我创建了一个
label
,它将更新UI
中的counter
值。 handler
- 当cell
被移出屏幕timer
- 在cell
中安排timer
timeinterval = 1
counter
- 每个cell
的当前
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
}
}
在上面的代码中,
timerArr
- 跟踪tableView
中每个cell
的counter
值。- 在
tableView(_:cellForRowAt:)
中,使用handler
更新每个cell
的counter
我们之前在CustomCell
中创建。
关于ios - Tableview Swift 中的多个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56463486/