Alexander Wad
Alexander Wad

Reputation: 1

Swift enable TableView reload while sliding through the view

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.

Upvotes: 0

Views: 227

Answers (1)

COSMO BAKER
COSMO BAKER

Reputation: 457

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.

Upvotes: 1

Related Questions