Search code examples
iosswiftuicollectionviewuicollectionviewflowlayout

Collection view first cell size issue


i have to hide some of the cells of uicollectionview based on my api response.

i am setting cell size to zero in collectionview's sizeForItemAtIndexPath method based on my json response value.

but even after setting the size to zero the cell which is at 0th index is always visible.

i can not filter out and remove the data from the array. i need that data for some operations.

my UICollectionView datasource method.

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 5
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! testCell
    cell.lblTest.text = "\(indexPath.item)"
    return cell
}

my flow layout delegate method.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if (indexPath.section == 0 && indexPath.item == 0) || (indexPath.section == 1 && indexPath.item == 0){
            return CGSize(width: 0, height: 0)
        }
        return CGSize(width: 50, height: 50)
    }

expected result is the cell at 0th index in 0 and 1 section is hidden but it is still displayed. enter image description here


Solution

  • You shouldn't do this by trying to set the size to 0. If you set it to 0 underlying code reads that as trying to automatically size it for you (this is why setting it to a small value close to 0 looks like it almost works). What you want to actually do is just adjust your data source. So when it asks for the number of items return the amount without the items that you want hidden, and cellForItem should just take into account that the item isn't there.