ios - 滚动父 View 的 CollectionView 以在模式关闭之前显示单元格

标签 ios swift uicollectionview

我正在尝试模仿 iPhoto 自定义动画,将图像从全屏缩小为缩略图。怪癖之一是,如果您以全屏方式打开图像,然后滑动足够多的距离,以便您正在查看的图像的相关缩略图在父 View 的 Collection View 中不可见,则需要将其滚动到可见 < em>在关闭模态之前。这样图像就有了一个可以动画化的缩略图。

我正在动画师中调用一个方法来执行此操作,但是当后续调用恰好检索可见单元格的 ImageView 时,它会崩溃,因为 Collection View 尚未滚动。我尝试过延迟,但没有帮助。

// 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)
  }
}

最后,委托(delegate)方法崩溃的地方:

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

感谢任何帮助!

最佳答案

我明白了。在崩溃时,我po collectionView'd并注意到contentOffset是它应该是的,但是cellForItemAt:没有被调用。所以我尝试强制 CollectionView 进行布局:

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

这成功了。我认为 iOS 正在优化,并且只会在下一个布局周期中更新它。

关于ios - 滚动父 View 的 CollectionView 以在模式关闭之前显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092713/

相关文章:

ios - 移动 UICollectionView 项目

ios - 添加 UIButton 以覆盖在 UITableView 之上

ios - 将 24 小时制日期对象转换为 12 小时制日期对象

ios - UICollectionview 在错误的地方更新随机图像

ios - 如何在 iOS 的 swift 中上传 gif 图片

iOS 应用程序在恢复购买后提示用户使用密码 "Confirm Your In-App Purchase"

ios - 在 UICollectionViewCell 的 subview 上调用 removeFromSuperview 在第一次加载时不起作用,仅当单元格被重用时

ios - 重用 uitextfield 进行输入验证

ios - textViewDidChangeSelection 方法认为 textView.text 为空

ios - View Controller Containment 共享父对象