简体   繁体   中英

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

用户触摸/拖动表格视图时,时间标签停止更新

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM