Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide / unhide section in Collection View

I have a collection view, this collection view has 3 section:

A

B

C

Then I want to hide section B, then it will look like:

A

C

I have tried

collectionView.deleteSections(NSIndexSet(index: 1))

but it crashes and says:

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

like image 866
Khuong Avatar asked Nov 30 '25 04:11

Khuong


1 Answers

If you ask the collection view to update itself adding/removing sections or cells, you also have to update your delegate methods in order to return the right number.

I write some code on the fly, use it as a starting point to understand the concept:

var sections = 3
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return sections
}

func removeSectionOne() {
   sections = 2
   collectionView.deleteSections(NSIndexSet(index: 1))
   // At this point the collection view will ask again for the number of sections and it will be updated
}
like image 107
Alessandro Orrù Avatar answered Dec 02 '25 18:12

Alessandro Orrù



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!