2

I am new in swift and I am facing problem to get current indexpath of collection view my code is like this

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in SliderCollectionView.visibleCells {
        let indexPath = SliderCollectionView.indexPath(for: cell)
        print(indexPath)
    }
}

I am getting indexPath but like this Optional([0, 2]) But I need it as 2

iGatiTech
  • 2,306
  • 1
  • 21
  • 45
Mujtaba
  • 97
  • 1
  • 7

3 Answers3

5

You need if-let

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in SliderCollectionView.visibleCells {
      if let row = SliderCollectionView.indexPath(for: cell)?.item {
           print(row) 
      }
    }
}

you can access the visible indices directly

 for index in SliderCollectionView.indexPathsForVisibleItems {
    print(index.item)
 }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Change indexPath with indexPath.row

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in SliderCollectionView.visibleCells {
        let indexPath = SliderCollectionView.indexPath(for: cell)
        print(indexPath.row)

    }
}
Nick
  • 875
  • 6
  • 20
-2

Try with this

if let indexPath = collectionView.indexPath(for: cell) {
   print(indexPath.row)
}
AGM Tazim
  • 2,213
  • 3
  • 16
  • 25