如何在显示屏幕之前获取 UICollectionView 中的单元格框架



在将 UICollectionViewController 的集合视图中的前 3 个单元格的位置推送到导航堆栈之前,获取前 3 个单元格的位置的最佳方法是什么?

例如:

let collectionViewController = SomeCollectionViewControllerSubclass(data: someData)
// @ TODO: get the frames of the first three cells here so I can create a fancy transition
self.navigationController.pushViewController(collectionViewController, animated: true)

这是我尝试过的:

let collectionViewController = SomeCollectionViewControllerSubclass(data: someData)
// force load the view
let view = collectionViewController.view
// try to get a cell directly (result: nil)
println(collectionViewController.collectionView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)
// try to ask the layout for the cell attributes (result: CGRectZero)
println(collectionViewController.collectionView.collectionViewLayout.initialLayoutAttributesForAppearingItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)))
self.navigationController.pushViewController(collectionViewController, animated: true)
如果

可以的话,你必须自己计算它。

单元格视图显示在屏幕上之前,您无法访问它们,因为当系统需要显示它们时,将创建它们,以避免在不必要的情况下创建它们。

因此,您必须依靠您的单元格布局知识来了解是否可以评估它们的位置(例如,您的单元格是否始终具有相同的高度)。

最新更新