Armin
Armin

Reputation: 1756

UILabel text updating with NSTimer but not while touch/dragging UITableView (gif example)

I'm new to swift and iOS development but not at all new to programming. I am building a small stopwatch app as my first demo project. It is a clone of the built-in iOS8 stopwatch app with some small variations, but mostly exactly the same.

I am nearly finished with the app and I noticed an issue with the UILabels being updated. They work perfectly, but they are not updating when the user clicks and drags the table view beneath the timer. The timer keeps running just fine, but the time is not being updated to the UILabels. It only beings updating again when the user lets go of the UITableView.

Here is the example I recorded

Time label stops updating while user touch/drags the tableview

Does anyone know why this is happening? Or how to prevent it? In the post here NSTimer gets disturbed while scrolling the UITableView in iphone it seems like the issue is the NSTimer is running on the main thread, which is where all UI rendering takes place.

I suppose I'm supposed to run the NSTimer on another thread. Or maybe the UITableView on another thread. How would I run these as separate threads in Swift? This post NSTimer not working while dragging a UITableView seems to explain it well for Objective-C. And it actually explains that it's not that the NSTimer needs to run on another thread, but that it needs to be configured to run in all common modes. Does anyone know how this can be implemented in Swift? Or if it is the correct answer in this case?

Upvotes: 1

Views: 574

Answers (1)

davbryn
davbryn

Reputation: 7176

The swift code should be very similar to the Objective-C code when adding the timer, so (from the linked answer):

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

would become

NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)

Upvotes: 4

Related Questions