小编lea*_*ift的帖子

如何在Swift中使用NSTimer和NSNotificationCentre更新UITableViewCells

注意:请在Swift中寻求答案.

我正在做的事情:

  • 让tableview单元每1秒更新一次,并显示实时倒计时.

我目前是怎么做的:

  • 我有一个包含标签的单元格的tableview.

  • 生成单元格后,它们会调用一个函数来计算今天和存储的目标日期之间的时间,并显示标签中剩余的倒计时时间.

  • 为了让单元格每秒更新标签,我使用一个NSTimer每秒重新加载tableview.

  • 问题:倒计时有效,但是当我尝试执行"滑动到删除"操作时,因为NSTimer重新加载了tableview,它会重置刷过的单元格以便不再刷卡,当然这对最终用户来说是不可接受的.

我正在尝试/潜在的解决方案

  • 我听说更好的方法是使用NSNotificationCenter触发器NSTimer并为每个单元添加侦听器.每隔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 {
            // …
    Run Code Online (Sandbox Code Playgroud)

uitableview nstimer nsnotificationcenter ios swift

7
推荐指数
1
解决办法
5433
查看次数

标签 统计

ios ×1

nsnotificationcenter ×1

nstimer ×1

swift ×1

uitableview ×1