在Swift中获取Visible IndexPath UICollectionView

Sha*_*i C 11 ios uicollectionview swift

如何获得visible IndexPath,而scrollingcollectionView我提到的许多链接1,链接2但是indexPathForCell在斯威夫特不支持.

Dar*_*ari 17

你试过代理功能吗?

public func indexPathsForVisibleItems() -> [NSIndexPath]
Run Code Online (Sandbox Code Playgroud)

要么

collectionView.indexPathsForVisibleItems()
Run Code Online (Sandbox Code Playgroud)

这些必须给你你想要的.


Anb*_*hik 7

试试这个

代表

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
for cell in yourCollectionViewname.visibleCells()  as [UICollectionViewCell]    {
   let indexPath = yourCollectionViewname.indexPathForCell(cell as UICollectionViewCell)

    NSLog("%@", indexPath)
}
}
Run Code Online (Sandbox Code Playgroud)

选择-2

按钮单击

  var point : CGPoint = sender.convertPoint(CGPointZero, toView:yourCollectionViewname)
var indexPath =yourCollectionViewname!.indexPathForItemAtPoint(point)
Run Code Online (Sandbox Code Playgroud)

获取所有项目

你可以使用indexPathsForVisibleRows

返回索引路径数组,每个索引路径标识接收器中的可见行.

  • (NSArray*)indexPathsForVisibleItems;
var visible: [AnyObject] = yourCollectionViewname.indexPathsForVisibleItems
var indexpath: NSIndexPath = (visible[0] as! NSIndexPath)
Run Code Online (Sandbox Code Playgroud)


kyl*_*kyl 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)

}
Run Code Online (Sandbox Code Playgroud)


Hem*_*ang 5

快速,安全的方式获得可见的物品

if let indexPaths = self.collectionView.indexPathsForVisibleItems {
    //Do something with an indexPaths array.
}
Run Code Online (Sandbox Code Playgroud)