【发布时间】:2015-02-16 04:26:45
【问题描述】:
注意:请在 Swift 中寻求答案。
我想做的事:
- 让表格视图单元格每 1 秒更新一次并实时显示 倒计时。
我目前的情况:
我有一个包含标签的单元格的表格视图。
生成单元格时,它们会调用一个函数来计算今天与存储的目标日期之间的时间,并在标签中显示剩余的倒计时时间。
为了让单元格每秒更新一次标签,我 使用
NSTimer每秒重新加载表格视图。问题:倒计时有效,但是当我尝试执行滑动删除操作时,因为
NSTimer重新加载了 tableview,它重置了 滑动单元格使其不再被滑动,这对于最终用户来说当然是不可接受的。
我正在尝试什么/可能的解决方案
我听说更好的方法是使用由
NSTimer触发的NSNotificationCenter并向每个单元格添加侦听器。每 1 秒从NSNotificationCenter发送一个“广播”,单元格将收到“广播”并更新标签。-
我尝试在生成新单元格的代码部分中为每个单元格添加一个侦听器:
// Generate the cells override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Tablecell", forIndexPath: indexPath) as UITableViewCell let countdownEntry = fetchedResultController.objectAtIndexPath(indexPath) as CountdownEntry // MARK: addObserver to "listen" for broadcasts NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateCountdownLabel", name: mySpecialNotificationKey, object: nil) func updateCountdownLabel() { println("broadcast received in cell") if let actualLabelCountdown = labelCountdown { // calculate time between stored date to today's date var countdownValue = CountdownEngine.timeBetweenDatesRealTime(countdownEntry.date) actualLabelCountdown.text = countdownValue } } 但观察者的选择器似乎只能在视图控制器级别定位功能,而不是在单元格中。 (我无法从单元格内触发“updateCountdownLabel”。当我在视图控制器级别创建同名函数时,可以调用该函数)
问题
- 所以我的问题是:这是正确的方法吗?
- 如果是,如何让侦听器在单元级别触发函数?
- 如果不是,那么在不中断滑动单元格操作的情况下实现此实时倒计时的最佳方法是什么?
提前感谢您的帮助!
【问题讨论】:
-
你试过用
reloadRowsAtIndexPaths(_ indexPaths: [AnyObject], withRowAnimation animation: UITableViewRowAnimation)代替reloadData吗? -
这就是我用来重新加载表格单元格的方式
func timerAction() { // update the countdown label with the countdown value //tableView.reloadData() }使用“reloadRowsAtIndexPaths”会避免取消单元格的滑动状态吗?如果我要在这种情况下使用“reloadRowsAtIndexPaths”,我会在哪里调用它? -
您可以避免在索引路径列表中滑动单元格。如果您可以直接访问标签来更新倒计时值,则根本不需要调用
reload。 -
太棒了。因此,使用这种方法,NSTimer 的选择器将定位一个使用“reloadRowsAtIndexPaths”的函数,该函数也有一个条件:如果滑动,不要重新加载?另外,NSNotificationCentre 是否仍然起作用还是应该被丢弃?
标签: ios uitableview swift nstimer nsnotificationcenter