VGDev
VGDev

Reputation: 303

How to delete sections in collection views

How can I delete individual sections from a controller view? I have a button in the header and everything is connected. Just not sure how can I write the code for 3 different sections.

My data model

var fire = [UIImages]
var water = [UIImages]
var air = [UIImages]

var fireLabel = [String]
var waterLabel = [String]
var airLabel = [String]

My cell configuration code

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    if indexPath.section == 0 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.fire.image = fireImages[indexPath.row]
        cell.fireLabel.text = fireNames[indexPath.row]


    return cell

    } else if indexPath.section == 1 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.water.image = waterImages[indexPath.row]
        cell.waterLabel.text = waterNames[indexPath.row]

        return cell

    } else {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.air.image = airImages[indexPath.row]
        cell.airLabel.text = airNames[indexPath.row]

        return cell

    }

}

And here is my button code, its in every header. What I want to do is that when you click on this button, it deletes that entire section. Again for each. But I can't seem to make it work.

//Delete Section Button
@IBAction func deleteSectionButton(sender: UIButton) {

    //Section tag
    let section = sender.tag

    //Update data model
    fireImages.removeAtIndex(section)
    fireNames.removeAtIndex(section)

    self.collectionView?.deleteSections(NSIndexSet(index: section))

}

I'm getting this error:

*** 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).'

But I don't know what it means.

Upvotes: 0

Views: 2882

Answers (1)

xmhafiz
xmhafiz

Reputation: 3538

you can just reload the collection view after updating your data. It will populate back your data proportionally to the collection view

self.collectionView.reloadData();

Upvotes: 0

Related Questions