1

I have a sectioned uicollectionview with nested cells that can be deleted on tap.

My goal is to display cells from the datasource if available, and if not, to show a "placeholder" cell stating no data is currently available.

My issue emerges on delete of a last remaining cell under a given section. My numberOfItemsInSection is 1 specifically for the "placeholder" cell but should be 0 to align to the datasource of 0 where no more data is available.

Any thoughts on workarounds?

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 3
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if sectionItems[section].count == 0 {
        return 1
    }
    else {
        return sectionItems[section].count
    }
}

func onTap() {
    self.sectionItems[indexPath.section]?.remove(at: indexPath.item)
    self.exampleCollectionView.deleteItems(at: [indexPath])
}

1 Answer 1

0

When you delete your last item, you need to instead reload for the "No Items" cell. Something like this should work:

func onTap() {
    sectionItems[indexPath.section]?.remove(at: indexPath.item)
    let isEmpty = sectionItems[indexPath.section]?.count ?? 0 == 0

    exampleCollectionView.performBatchUpdates({
        if isEmpty {
            self.exampleCollectionView.reloadItems(at: [indexPath])
        } else {
            self.exampleCollectionView.deleteItems(at: [indexPath])
        }
    }, completion: nil})
}

Essentially you need to tell the collectionView that there will still be one cell there after the update when the last item is removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.