首页 > 解决方案 > Swift - 如何以编程方式访问 collectionView 的 targetContentOffset.pointee.y

问题描述

当用户滑动时,我会运行一些代码,scrollViewWillEndDragging我需targetContentOffset.pointee.y要这样做:

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...
}

问题是我也做了一些自动滚动,用户不必滑动并且 cv 自动滚动。我仍然需要访问,targetContentOffset.pointee.y所以我可以对 visibleItem 做一些事情,但我它所在的方法不会在自动滚动时触发。

如何以编程方式访问 targetContentOffset.pointee.y?

标签: iosswiftuicollectionviewuiscrollview

解决方案


你可以试试

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)
  }
}

推荐阅读