Search code examples
iosswiftxcodecollectionviewuiviewanimationtransition

can't get frame of collectionViewCell item for transition


I am trying to transition a view into the imageView of a collectionViewCell of another viewController. In order to do that I need the frame of the imageView in the collectionViewCell converted to Window.

I am trying to do that using the following in viewWillAppear:

let indexPath = IndexPath(item: 0, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell
let boundingRect = cell.imageView.convert(cell.imageView.bounds, to: nil)

The size of the boundingRect is correct however the origin is at 0,0 for some reason and not where it should be.

I'm wondering if the problem is that the collectionView is not laid out yet and thus the origin is wrong. If that's the case, how can I force it to layout. I have tried:

collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()

But that also didn't change the origin.

How could I force the layout of the collectionView and get the frame of a particular cell (or imageView in that cell) prior to viewDidAppear. I would like to avoid doing it in viewWillLayoutSubviews or viewDidLayoutSubviews to prevent this from constantly being run.


Solution

  • According to https://developer.apple.com/documentation/uikit/uiview/1622498-convert we need:

    • view (collectionView.superview), where we want to get subview's location,
    • subview's frame (cell.imageView.frame)
    • and subview's superview or superview.superview etc, any view that contains subview's frame (cell)

    and we get

    let boundingRect = collectionView.superview.convert(cell.imageView.frame, from: cell)