How to reload section from collectionview

H.jenny picture H.jenny · Aug 1, 2016 · Viewed 11.4k times · Source

I tried to delete a cell from collectionview on didSelect method.

Deleting the data is working well.

But I'm getting this:

reason: 'Invalid update: invalid number of sections. The number of sections contained in the collection view after the update (1) must be equal to the number of sections contained in the collection view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

This is delete cell function:

func deleteMovie(cell: MoiveCollectionViewCell) {
var indexPath: NSIndexPath = self.collectionView!.indexPathForCell(cell)!
 // remove and reload data
 self.collectionView.deleteItemsAtIndexPaths([indexPath])
 self.collectionView.reloadSections(NSIndexSet(index: indexPath.section))
}

and numberOfSectionsInCollectionView func :

 func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    //number_per_section = 3 
    if manager.movie_List.count % number_per_section  == 0
    {
        return manager.movie_List.count / number_per_section
     }
    else {  
       return manager.movie_List.count / number_per_section  + 1
         }
}

I just want to reload number of sections. What should I add?

Answer

Edward picture Edward · Dec 1, 2017

You need to update the datasource first before you make the calls to:

 collectionView.deleteItemsAtIndexPaths([indexPath])
 collectionView.reloadSections(NSIndexSet(index: indexPath.section))

So first delete the object in your datasource model (array, dictionary etc).

Then you can just do this:

 let indexSet = IndexSet(integer: indexPath.section)
 collectionView.reloadSections(indexSet)