CollectionView: Sync `center.y` of UIView outside collection view and a view in a cellinside

I have a setup:

  • Collection view with compositional layout
  • a self sizing cell inside
  • a subview inside the cell
  • and unrelated view outside the collection view

I would like to:

  • modify the layout (constraints) of the cell inside the collection view with UIView.animate
  • trigger an animated layout update of collection view
  • synchronize the position of an unrelated view to the position of one of the subviews of a collection view cell

What I tried:

UIView.animate(withDuration: 0.25) {
     cellViewReference.updateState(state: state, animated: false)
     collectionView.collectionViewLayout.invalidateLayout()
     collectionView.layoutIfNeeded()
     someOtherViewOutsideCollectionView.center = cellViewReference.getPositionOfThatOneViewInWindowCoordinateSystem()
}

What I'm expecting:

  • after invalidateLayout, the layout update of the collection view is merely scheduled, but not yet performed
  • layoutIfNeeded forces an update on the collectionViewLayout + update on the frames of the views inside the UICollectionViewCells
  • all the frames become correct to what they will look like after the animation is performed
  • I call getPositionOfThatOneViewInWindowCoordinateSystem and it gives me the position of the view after the uicollectionview AND the cell's layout has updated

What happens instead:

  • getPositionOfThatOneViewInWindowCoordinateSystem returns me an old value
  • I am observing that the bounds of the cell didn't actually change during layoutIfNeeded
  • And moreover, the bounds change without animation, instantly

Question:

  • how to animate self sizing cell size change due relayout
  • how to synchronize outside views with collection views
Answered by isaacweisberg in 825248022

how to animate self sizing cell size change due relayout?

Turns out:

collectionView.performBatchUpdates {
    UIView.animate(withDuration: 0.25, animations: {
        cellViewReference.updateState(state: state, animated: false)
        cellViewReference.layoutIfNeeded()
    })
    collectionView.collectionViewLayout.invalidateLayout()
}

how to synchronize outside views with collection views?

Just don't, it doesn't end well...

Accepted Answer

how to animate self sizing cell size change due relayout?

Turns out:

collectionView.performBatchUpdates {
    UIView.animate(withDuration: 0.25, animations: {
        cellViewReference.updateState(state: state, animated: false)
        cellViewReference.layoutIfNeeded()
    })
    collectionView.collectionViewLayout.invalidateLayout()
}

how to synchronize outside views with collection views?

Just don't, it doesn't end well...

CollectionView: Sync `center.y` of UIView outside collection view and a view in a cellinside
 
 
Q