ios 在 Swift 中获取可见的 IndexPath UICollectionView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35740652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:38:42  来源:igfitidea点击:

Get Visible IndexPath UICollectionView in Swift

iosswiftuicollectionview

提问by Shangari C

How to get visible IndexPathwhile scrollingin collectionView,I referred many link1,link2But indexPathForCellis not supported in Swift.

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

回答by Dari

Have you tried delegate function?

您是否尝试过委托功能?

public func indexPathsForVisibleItems() -> [NSIndexPath]

or

或者

collectionView.indexPathsForVisibleItems()

these must give you what you wanted.

这些必须给你你想要的。

回答by Anbu.Karthik

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

选择 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

您可以使用 indexPathsForVisibleRows

Returns an array of index paths each identifying a visible row in the receiver.

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

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

回答by Hemang

Swift, safer way to get visible Items:

快速、更安全的获取可见项的方法

if let indexPaths = self.collectionView.indexPathsForVisibleItems {
    //Do something with an indexPaths array.
}

回答by hkg328

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)

}

回答by Ashvini

You can use method of UICollectionView as :

您可以将 UICollectionView 的方法用作:

let indexPath = NSIndexPath(item: value1, section: value2)