How to reset UICollectionView in Swift

Viewed 5414

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()
        }
    }
2 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

You need to remove every subview from each cell's contentView, not from your collection view

gameCollectionView.visibleCells.forEach { $0.contentView.subviews.forEach { $0.removeFromSuperview() } }

But, I'm not sure for what you need to override draw method. You should rather create what you need just once, for example in awakeFromNib and then you should just change properties of your image views, etc. depending on content, for this you purpose you can use collection view's data source method cellForItemAt.

Related