how to get indexPath for cell which is located in the center of UICollectionView

前端 未结 11 2248
慢半拍i
慢半拍i 2020-12-25 09:41

How can i find indexPath for cell in the middle of UICollectionView?

I have horizontal scrolling and only one big cell<

11条回答
  •  轮回少年
    2020-12-25 10:23

    Try this protocol...

    protocol CollectionVisibleMidCell {}
    extension CollectionVisibleMidCell where Self: UICollectionView {
    
        func getMidVisibleIndexPath() -> IndexPath? {
            var visibleRect = CGRect()
            visibleRect.origin = self.contentOffset
            visibleRect.size = self.bounds.size
            let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
            guard let indexPath = self.indexPathForItem(at: visiblePoint) else { return nil }
            return indexPath
        }
    }
    
    extension UICollectionView: CollectionVisibleMidCell {}
    

提交回复
热议问题