UICollectionView current visible cell index

后端 未结 16 1428
难免孤独
难免孤独 2020-11-29 16:52

I am using UICollectionView first time in my iPad application. I have set UICollectionView such that its size and cell size is same, means only onc

16条回答
  •  抹茶落季
    2020-11-29 17:17

    UICollectionView current visible cell index: Swift 3, 4 and 5+

    var visibleCurrentCellIndexPath: IndexPath? {
        for cell in self.collectionView.visibleCells {
            let indexPath = self.collectionView.indexPath(for: cell)
            return indexPath
         }
            
         return nil
    }
    

    As an Extension:

    extension UICollectionView {
      var visibleCurrentCellIndexPath: IndexPath? {
        for cell in self.visibleCells {
          let indexPath = self.indexPath(for: cell)
          return indexPath
        }
        
        return nil
      }
    }
    

    Usage:

    if let indexPath = collectionView.visibleCurrentCellIndexPath { 
       /// do something
    }
    

提交回复
热议问题