Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Visible IndexPath UICollectionView in Swift

How to get visible IndexPath while scrolling in collectionView,I referred many link1,link2 But indexPathForCell is not supported in Swift.

like image 710
Shangari C Avatar asked Mar 02 '16 07:03

Shangari C


People also ask

How does swift implement UICollectionView?

Add a CollectionView by pressing command shift L to open the storyboard widget window. Drag the collectionView onto the main view controller. Add constraints to the UICollectionView widget to ensure that the widget fills the screen on all devices. The foundation is now set up in the storyboard.

What is difference between Tableview and Collectionview?

When would you choose to use a collection view rather than a table view? Suggested approach: Collection views are there to display grids, but also handle entirely custom layouts, whereas table views are simple linear lists with headers and footers.


4 Answers

Have you tried delegate function?

public func indexPathsForVisibleItems() -> [NSIndexPath]

or

collectionView.indexPathsForVisibleItems()

these must give you what you wanted.

like image 184
Bibek Avatar answered Sep 26 '22 19:09

Bibek


Swift, safer way to get visible Items:

if let indexPaths = self.collectionView.indexPathsForVisibleItems {
    //Do something with an indexPaths array.
}
like image 32
Hemang Avatar answered Sep 25 '22 19:09

Hemang


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)
like image 9
Anbu.Karthik Avatar answered Sep 27 '22 19:09

Anbu.Karthik


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)

}
like image 6
Lead Developer Avatar answered Sep 28 '22 19:09

Lead Developer