How to get visible IndexPath
while scrolling
in collectionView
,I referred many link1,link2 But indexPathForCell
is not supported in Swift.
Asked
Active
Viewed 2.8k times
15
![](../../users/profiles/-1.webp)
Community
- 1
- 1
![](../../users/profiles/4373074.webp)
Shangari C
- 762
- 1
- 5
- 16
5 Answers
21
Have you tried delegate function?
public func indexPathsForVisibleItems() -> [NSIndexPath]
or
collectionView.indexPathsForVisibleItems()
these must give you what you wanted.
![](../../users/profiles/5690400.webp)
Dari
- 3,360
- 2
- 14
- 27
10
Swift, safer way to get visible Items:
if let indexPaths = self.collectionView.indexPathsForVisibleItems {
//Do something with an indexPaths array.
}
![](../../users/profiles/1603234.webp)
Hemang
- 25,740
- 17
- 113
- 171
8
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)
![](../../users/profiles/2783370.webp)
Anbu.Karthik
- 77,564
- 21
- 153
- 132
6
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)
}
![](../../users/profiles/7512762.webp)
Lead Developer
- 1,520
- 8
- 23
-4
You can use method of UICollectionView as :
let indexPath = NSIndexPath(item: value1, section: value2)
![](../../users/profiles/9059720.webp)
Ashvini
- 274
- 2
- 11
-
Your answer is completely irrelevant to the question – Henry Ngan Jun 12 '19 at 04:00