Reputation: 97
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
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
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
Reputation: 2217
Try with this
if let indexPath = collectionView.indexPath(for: cell) {
print(indexPath.row)
}
Upvotes: -2