NSFetchedResultsController触发动画完成后执行代码

时间:2016-06-04 16:57:23

标签: swift uitableview animation core-data

我希望在NSFetchedResultsController完成动画移动部分之间的tableview行后执行滚动动画。

当我关闭视图控制器时,会发生该部分的更新。这会触发tableview的动画,它可以正常工作。在这个动画之后,我希望tableview滚动到新位置。但是,在动画结束之前滚动开始不起作用。

self.dismissViewControllerAnimated(true, completion: {
  shoppingItem.category = self.categoryTextField.text // this line triggers the move between sections

  dispatch_async(dispatch_get_main_queue(), {
  tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
    do {
      try self.coreDataStack.context.save()
    } catch {
      fatalCoreDataError(error)
    }
  })
})

我意识到解决方案在于管理线程,但我无法弄清楚如何正确设置它。

解决方案:

通过将滚动延迟一秒,动画可以正常工作:

var time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 1 * Int64(NSEC_PER_SEC))

dispatch_after(time, dispatch_get_main_queue(), {
      self.indexPathOfChangedItem = self.fetchedResultsController.indexPathForObject(shoppingItem)
      self.itemsTableView.scrollToRowAtIndexPath(self.indexPathOfChangedItem, atScrollPosition: .Bottom, animated: true)
 })

请注意,名为indexPathOfChangedItem的新索引路径的定义也必须在延迟调用中,因为在NSFetchedResultsController触发的动画完成之前,此索引路径不是最新的。

1 个答案:

答案 0 :(得分:1)

FRC没有做动画,它只是观察变化并告诉你,然后你的代码会告诉表视图并且它会动画。

动画没有参数告诉你它什么时候完成或指定它需要多长时间:-(用Apple提升雷达。

简单的选项是猜测动画运行多长时间,并在动画后延迟运行滚动后发送。找到适当的等待时间可能是反复试验,一旦发现它不可能改变/与其他设备不同。

相关问题