计算哪个图像用户在水平集合视图上,启用分页

时间:2017-03-25 04:29:58

标签: ios swift uicollectionview

我有一个名为imageArray = [" one"," two",..." eight"]的数组。它用图像填充集合视图。前提条件:单元格在视图中居中,几乎占据了集合视图/视图的大部分。图像视图位于顶部,仅比单元格小一点。好的,现在我需要计算用户所在的图像。因此,如果用户滚动到图像3,我需要一种方法来计算3.我是ios编程的新手,当涉及到集合视图时,只是发现它们,并需要一些帮助。 这是一些代码(基本设置)

 class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var myCollectionView: UICollectionView!

@IBOutlet var mainView: UIView!

var imageArray = ["one", "two", "three", "four", "five", "six", "seven", "eight"]
     func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UserFeedCollectionViewCell
    cell.myImage.image = UIImage(named: imageArray[indexPath.row])
    cell.myImage.layer.cornerRadius = 12.0
    cell.myImage.clipsToBounds = true
    return cell
}

2 个答案:

答案 0 :(得分:1)

<强>解决方案

因此,当您想知道屏幕上哪个单元格可见时,

  1. 使用属性visibleCells,它将为您提供当前在屏幕上可见的单元格数组。

  2. 使用属性indexPathsForVisibleItems,它将为您提供所有可见单元格的indexPath数组。

  3. 有关信息

    UICollectionView中您正在使用dequeue属性。 dequeue属性的工作方式如下:

    让您拥有N个单元格,并且屏幕上可以显示 V 单元格,然后记录 V+1 单元格并在滚动后释放来自早期细胞的记忆并将其传递给新的可见细胞。

    希望它对你有所帮助。

答案 1 :(得分:0)

你应该做的是:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var aPoint = CGPoint()
    collectionView.indexPathForItem(at: aPoint)
}

一旦你有索引,比如屏幕的中心或UICollectionView,你就可以找出行,从而找出图像。

相关问题