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 - 旋转时未调用 UICollectionViewDelegateFlowLayout 方法

ios - 未调用 targetContentOffsetForProposedContentOffset

ios - 从 iTunes 下载 "Non-App Store"iOS 应用程序

ios - 如何在swift中为每一行分配不同的颜色

ios - UICollectionView ImageView 问题

swift - 无法将 Int 类型的值转换为预期的参数类型 IndexPath(核心数据)?

php - 在登录检查 PHP 和 SWIFT 时抛出相同的响应

ios - 添加多个 subview 时 ScrollView 不滚动

ios - 撰写电子邮件时设置 UINavigationBar 标题颜色

ios - 我将如何在 Swift 中创建一个 UIAlertView?