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

前端 未结 11 2252
慢半拍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条回答
  •  梦毁少年i
    2020-12-25 10:20

    For some of you that might be experiencing some troubles on getting the center, please look at this potential solution:

     func centerCell()->UICollectionViewCell? {
          // Asuming your scrolling is horizontal
          let viewHorizontalCenter =  self.view.bounds.width / 2
          let center = CGPoint(x: viewHorizontalCenter, y: self.collectionView.center.y)
    
          let convertedPoint = self.view.convert(center, to: self.unitsCollectionView)
    
          let center = CGPoint(x: self.view.bounds.width / 2, y: self.unitsCollectionView.center.y)
          let convertedPoint = self.view.convert(center, to: self.unitsCollectionView)
          for cell in unitsCollectionView.visibleCells {
              if cell.frame.contains(convertedPoint) {
                  print("Hello")
                  return cell
              }
          }
          return nil
        }
    

提交回复
热议问题