1

I have an array called imageArray = ["one", "two", ... "eight"]. And it fills a collection view with images. Preconditions: The cell is centered in the view and pretty much takes up the majority of the collectionview/view. The image view is on top and is just a little smaller than the cell. Ok so now I need to count which image the user is on. So if the user scrolls to image 3 I need a way to count 3. I am new to ios programming when it comes to collection views, just found out about them, and need some help. Here is some code (basic setup)

 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
}
rmaddy
  • 298,130
  • 40
  • 468
  • 517
Nivix
  • 131
  • 1
  • 11

2 Answers2

1

Solution

So when you wanted to know which cell is visible on the screen then

  1. Use property visibleCells, it will gives you array of cells which is currently visible on screen.

  2. Use property indexPathsForVisibleItems, it will gives you array of indexPath of all visible cells.

For info

In UICollectionView you are using dequeue property. The dequeue property works something like this :

let you have N cells and V cells are possible on the screen then it takes memory of V+1 cell and after scrolling it releases the memory from the early cell and give it to new visible cell.

Hope it helps you.

dahiya_boy
  • 7,885
  • 1
  • 25
  • 39
0

What you should do is this:

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

once you have the index for, let's say the center of the screen or UICollectionView, you can figure out the row and thus the image.

Jay
  • 2,431
  • 1
  • 14
  • 26