Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset UICollectionView in Swift

I am developing a card game using UICollectionView. I override the draw() function of the UICollectionViewCell to arrange my images when load the cells. Every new game, i change the number of cards in the game. So the number and size of the cells change. I have to do all operations for UICollectionView in the viewWillAppear() method because of the third part library i use. My question is that how to reset all the works which done over the UICollectionView before. I want clear UICollectionView during each game without loading UIViewController again. Wanna do it in viewWillAppear() method. I want to clear UICollectionView because my images overlap if don't have clear UICollectionView in new game.

Note : I removed all the subviews from UICollectionView like below, but it didn't work

   let subViews = gameCollectionView.subviews

    if subViews != nil {
        for view in subViews {
            view.removeFromSuperview()
        }
    }
like image 217
nihasmata Avatar asked Jan 30 '26 18:01

nihasmata


1 Answers

Clearing the collection is from clearing it's dataSource array like

arr = []
gameCollectionView.reloadData()

if you need to clear the cell then do it inside cellForRowAt

let cell = ///
cell.contentView.subviews//// clear here

or override

override func prepareForReuse() {
 super.prepareForReuse()
 // clear any subview here
}

if you correctly assign values for all properties of the collection cell every run of cellForRowAt without adding subviews , then you'll have no overlappings

like image 101
Sh_Khan Avatar answered Feb 02 '26 10:02

Sh_Khan



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!