Search code examples
iosswiftuicollectionviewuiscrollview

Swift -How to programmatically access collectionView's targetContentOffset.pointee.y


When a user swipes, I run some code in scrollViewWillEndDragging and I need the targetContentOffset.pointee.y to do it:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let yAxis = targetContentOffset.pointee.y

    let visibleItem = Int(yAxis / collectionView.frame.height)
    
    // do something with visibleItem based on cell's current vertical scroll position...
}

The issue is I also do some autoscrolling, where the user doesn't have to swipe and the cv auto scrolls. I still need access to the targetContentOffset.pointee.y so I can do something with with the visibleItem but I the method it's in doesn't trigger on autoscroll.

How can I programmatically access the targetContentOffset.pointee.y?


Solution

  • You can try

    let index = IndexPath(item: xyz, section: 0) 
    collectionView.scrollToItem(at:index, at: .centeredVertically, animated: true)
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
      if let cell = collectionView.cellForItem(at:index) {
        let frame = collectionView.convert(cell.frame,nil)
      }
    }