Mujtaba
Mujtaba

Reputation: 97

How to get current index path of collection view in swift

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

Upvotes: 2

Views: 7057

Answers (3)

Nick
Nick

Reputation: 875

Change indexPath with indexPath.row

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

    }
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

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)
 }

Upvotes: 5

AGM Tazim
AGM Tazim

Reputation: 2217

Try with this

if let indexPath = collectionView.indexPath(for: cell) {
   print(indexPath.row)
}

Upvotes: -2

Related Questions