I am using a Timer to increment an Int and with a press of a button I record the current number in an array. I also have a TableView to show the contents of the array. Everything works fine, except that if I grab the TableView and move it even a bit to scroll, the Timer hangs until I release the TableView.
How can I keep the Timer running regardless of what I do to the TableView?
Here is my 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
}
}
If you need it you can see the whole project on: https://github.com/Fr3qu3ntFly3r/TimerTest
Thank you for the help in advance.