How to get visible IndexPath
while scrolling
in collectionView
,I referred many link1,link2 But indexPathForCell
is not supported in Swift.
Asked
Active
Viewed 3.1k times
15

Community
- 1
- 1

Shangari C
- 792
- 1
- 5
- 17
5 Answers
21
Have you tried delegate function?
public func indexPathsForVisibleItems() -> [NSIndexPath]
or
collectionView.indexPathsForVisibleItems()
these must give you what you wanted.

Bibek
- 3,689
- 3
- 19
- 28
11
Swift, safer way to get visible Items:
if let indexPaths = self.collectionView.indexPathsForVisibleItems {
//Do something with an indexPaths array.
}

Hemang
- 26,840
- 19
- 119
- 186
9
try this
On delegate
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
for cell in yourCollectionViewname.visibleCells() as [UICollectionViewCell] {
let indexPath = yourCollectionViewname.indexPathForCell(cell as UICollectionViewCell)
NSLog("%@", indexPath)
}
}
Choice-2
on Button Click
var point : CGPoint = sender.convertPoint(CGPointZero, toView:yourCollectionViewname)
var indexPath =yourCollectionViewname!.indexPathForItemAtPoint(point)
Get visible All Items
you can use indexPathsForVisibleRows
Returns an array of index paths each identifying a visible row in the receiver.
- (NSArray *)indexPathsForVisibleItems;
var visible: [AnyObject] = yourCollectionViewname.indexPathsForVisibleItems
var indexpath: NSIndexPath = (visible[0] as! NSIndexPath)

Anbu.Karthik
- 82,064
- 23
- 174
- 143
5
This will work fine.
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let visibleIndex = Int(targetContentOffset.pointee.x / collectionView.frame.width)
print(visibleIndex)
}

Lead Developer
- 1,146
- 10
- 26
-4
You can use method of UICollectionView as :
let indexPath = NSIndexPath(item: value1, section: value2)

Ashvini
- 342
- 3
- 11
-
Your answer is completely irrelevant to the question – Henry Ngan Jun 12 '19 at 04:00