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

前端 未结 11 2253
慢半拍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:16

    Swift:

    extension UICollectionView {
    
    var centerPoint : CGPoint {
    
        get {
            return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
        }
    }
    
    var centerCellIndexPath: IndexPath? {
    
        if let centerIndexPath: IndexPath  = self.indexPathForItemAtPoint(self.centerPoint) {
            return centerIndexPath
        }
        return nil
    }
    }
    

    Usage :

    if let centerCellIndexPath: IndexPath  = collectionView.centerCellIndexPath {
                    print(centerCellIndexPath)
                }
    

    Swift 3:

    extension UICollectionView {
    
    var centerPoint : CGPoint {
    
        get {
            return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
        }
    }
    
    var centerCellIndexPath: IndexPath? {
    
        if let centerIndexPath = self.indexPathForItem(at: self.centerPoint) {
            return centerIndexPath
        }
        return nil
    }
    }
    

提交回复
热议问题