模式解雇之前滚动父视图的CollectionView以显示单元格

时间:2017-05-21 02:54:19

标签: ios swift uicollectionview

我试图模仿iPhoto自定义动画,将图像从全屏缩小到缩略图。其中一个怪癖是如果您以全屏模式打开图像,然后滑动到足以使您正在查看的图像的相关缩略图在父视图的集合视图中不可见,则需要将其滚动到可见< em>在解雇模态之前。这样,图像就会有一个动画缩略图。

我正在调用一个方法来从我的动画师中执行此操作,但是当后续调用发生检索可见单元格的imageview时,它会崩溃,因为集合视图尚未滚动。我试过实施延迟,但没有用。

// controller with the collection view    
guard let toVC = transitionContext.viewController(forKey: .to) as? GalleryViewController else { return }

// controller with image
guard let fromVC = transitionContext.viewController(forKey: .from) as? PhotoViewController else { return }

// this performs the scroll; implementation below
toVC.scrollToShow(index: fromVC.selectedIndex)

// this is where it crashes, as the cell doesn't exist yet
guard let toImageView = delegate?.imageView(for: fromVC.selectedIndex) else { return }

显示单元格的代码:

func scrollToShow(index: Int) {
  let indexPath = IndexPath(row: index, section: 0)
  if collectionView.cellForItem(at: indexPath) == nil {
    // only scroll the cell to the top if it isn't visible
    collectionView.scrollToItem(at: indexPath, at: .top, animated: false)
  }
}

最后,崩溃的地方是委托方法:

func imageView(for selectedIndex: Int) -> UIImageView {
  let cell = collectionView.cellForItem(at: IndexPath(row: selectedIndex, section: 0)) as! GalleryCell
  return cell.imageView
}

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我明白了。在崩溃时,我po collectionView'并注意到contentOffset本来就是这样,但cellForItemAt:没有被调用。所以我尝试强制使用collectionView进行布局:

...
collectionView.scrollToItem(at: indexPath, at: .top, animated: false)
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
...

这很有效。我想iOS正在优化,只会在下一个布局周期中更新它。

相关问题