table 视图中的重新加载行被无意中延迟

Reloading row in table view is delayed inadvertently

在 tableView 中选择一个单元格时,我需要重新加载该行并设置一些计时器以在特定日期触发 AVAudioPlayers(此设置需要几秒钟,计时器已经开始触发, 不过,如预期的那样)。

但是,重新加载 table 视图行(有效突出显示该行)会延迟片刻。

为了保持良好的 UI 体验,我需要首先重新加载该行。

我试过将重新加载部分放在主线程中,如这里所建议的:

由于某些原因这将不起作用:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  // do some things

  dispatch_async(dispatch_get_main_queue(), {
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
  })

  setupTimersToFireAtDate() 
}

func setupTimersToFireAtDate() {
  let start = NSDate()
  // These are Float as they will be calculated with other Float values
  var accumulatedTime: Float = 0.0
  var elapsedTime: Float = 0.0

  for event in events {
    var player = AVAudioPlayer()
    accumulatedTime += event.time

    do {
      // the urls array keeps urls to the sounds. For this example, I've set the index to be random, since it doesn't really matter.
      player = try AVAudioPlayer(contentsOfURL: urls[Int.random])
      // Players need to be maintained in order to playback, each player is removed with the audioPlayerDidFinishPlaying AVAudioPlayerDelegate method.
      players += [player]
    } catch let error as NSError {
      loadError = error
    }

    elapsedTime = Float(NSDate().timeIntervalSinceDate(start))

    // Some other calculations in between here.

    player.prepareToPlay()
    player.delegate = self
    player.currentTime = 0.0

    player.playAtTime(player.deviceCurrentTime + (NSTimeInterval(accumulatedNoteTime - elapsedTime)))
  }
}

我可能遗漏了一些东西,因为我不知道为什么这不起作用。

非常感谢任何帮助!

最简单的解决方案是延迟对 setupTimersToFireDate 的调用,这样对 reloadRowsAtIndexPaths 的调用可以立即 运行。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // do some things

    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)

    dispatch_async(dispatch_get_main_queue(), {
        setupTimersToFireAtDate() 
    })
}