Search code examples
iosswiftswift3

how to hide particular cells in collectionview in swift


In my project i got a array which i am loading on my collectionview

var dataSource = ["@", "@", "1", "2", "3", "4", "5", "6", "7", "8" , "9", "10", "@", "@"]

for the string "@" i want to hide that particular cell. so initially i was trying to do it using indexpath and then tried to check if my array position got value "@". But i am unable to hide it properly as some other cell would get changed on scroll

So this what i have done on my cellForItemAt :

if dataSource[indexPath.row] == "@" {

            cell.contentView.isHidden = true
            cell.layer.borderColor = UIColor.white.cgColor

        }

Things to be considered its scrolling horizontally and this is my sizeForItemAt :

func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {


        return CGSize(width: (self.numberCollectionView?.bounds.size.width)!/5 - 3, height: (self.numberCollectionView?.bounds.size.width)!/5 - 3 )
    }

Solution

  • You are reusing the cell, so you need to add else part also of that condition to set isHidden to false and default borderColor.

    if dataSource[indexPath.row] == "@" {
    
        cell.contentView.isHidden = true
        cell.layer.borderColor = UIColor.white.cgColor
    }
    else {
        cell.contentView.isHidden = false
        cell.layer.borderColor = UIColor.black.cgColor //Set Default color here
    }
    

    Also if you doesn't want to show the cell that why don't you remove that element from your array using filter.

    dataSource = dataSource.filter { $0 != "@" }
    

    And now just reload the collectionView.