0

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,142
  • 1
  • 17
  • 42
Mujtaba
  • 67
  • 6

3 Answers3

1

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)
 }
Sh_Khan
  • 86,695
  • 6
  • 38
  • 57
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
  • 787
  • 5
  • 17
-1

Try with this

if let indexPath = collectionView.indexPath(for: cell) {
   print(indexPath.row)
}
AGM Tazim
  • 1,954
  • 2
  • 13
  • 24