TmSmth
TmSmth

Reputation: 452

1 section and 2 cells but 4 indexPath.row

Swift 4. I want to return two cells in one section, so in my class CollectionViewController I do :

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1 } 

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 2 }

I see two cells but if I print indexPath.row in the code below (still in the same class), I see 0 1 0 1. Why is it not only one 0 1as I have only two cells in one section ?

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
    print(indexPath.row)
    return cell 
}

Upvotes: 1

Views: 279

Answers (1)

rbaldwin
rbaldwin

Reputation: 4848

cellForItemAt is getting called four times. Your numberOfItemsInSection is hard-coded for 2. When the view loads cellForItemAt is called twice (once for each cell). It is then getting called twice again when you call reloadData() from your DispatchQueue.main.async closure.

Updated - How to avoid the first call:

You need to store your cell data in an array, and only populate the array just before you call reloadData(). Thus, the array will be empty when the view is first loaded.

var yourArray = [YourObject]() //Empty Array    

//..

DispatchQueue.main.async {
    //append your two items to the yourArray
    yourArray.append(/*cell1data*/)
    yourArray.append(/*cell2data*/)
    self.collectionView?.reloadData()
}

//..

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return yourArray.count
}

Upvotes: 1

Related Questions