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,240
  • 1
  • 19
  • 43
Mujtaba
  • 97
  • 1
  • 7

3 Answers3

4

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
  • 93,445
  • 7
  • 57
  • 76
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
  • 817
  • 6
  • 18
-1

Try with this

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