0

In my application I have a timer which every .1 seconds increases an integer by 1. This integer is displayed in a table view cell. To show this integer increasing, I have another timer in my table view controller which every .1 seconds reloads the tableview. This works perfectly fine, the only issue I am encountering is that whilst I am sliding through the table view, the increase in value stops; as soon as I let go of the table view in continues increasing. I would love to know a way to disable this behavior, in order that the table view continues reloading even whilst the user is scrolling through it.

  • 1
    Possible duplicate of [How to update UITableViewCells using NSTimer and NSNotificationCentre in Swift](https://stackoverflow.com/questions/28534518/how-to-update-uitableviewcells-using-nstimer-and-nsnotificationcentre-in-swift) – J. Doe Feb 22 '18 at 19:15
  • I had the same problem, the answer I linked works perfectly – J. Doe Feb 22 '18 at 19:15

1 Answers1

1

By using scheduledTimerWithTimeInterval, your timer is scheduled on the main run loop for the default modes, preventing your timer from firing when your run loop is in a non-default mode (tapping or swiping).

Schedule your timer for all common modes:

@IBOutlet weak var tableView: UITableView!
var count = 0 {
    didSet {
        tableView.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (time) in
        self.count += 1
        print(self.count)
    })
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) // the magic
    tableView.delegate = self
    tableView.dataSource = self
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = String(count)
    return cell
}

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

This code works.

COSMO BAKER
  • 337
  • 4
  • 16