我正在使用計時器增加一個Int並按下按鈕我將當前數字記錄在一個數組中。我也有一個TableView來顯示數組的內容。一切工作正常,除了如果我抓住TableView,甚至有點滾動,定時器掛起,直到我釋放TableView。Swift 3.2 - 計時器()與TableView
無論我對TableView做什麼,該如何保持Timer運行?
這裏是我的ViewController.swift:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var myTableView: UITableView!
var timer = Timer()
var isTimerOn = false
var counter = 0
var samples: [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
}
@IBAction func startStopButton(_ sender: Any) {
switch isTimerOn {
case true:
timer.invalidate()
isTimerOn = false
case false:
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in
self.counter += 1
print(self.counter)
}
isTimerOn = true
}
}
@IBAction func recordButton(_ sender: Any) {
samples.insert(counter, at: 0)
myTableView.reloadData()
}
}
extension ViewController {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return samples.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyCell
cell.number = samples[indexPath.row]
return cell
}
}
如果你需要它,你可以看到整個項目上: https://github.com/Fr3qu3ntFly3r/TimerTest
感謝您的幫助提前。
檢查本網頁https://stackoverflow.com/questions/29204229/countdown-timer-on-uitableviewcell-scrolling-laggy-issue-of -uitableview – Rex