Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to hide particular cells in collectionview in swift

Tags:

ios

swift

swift3

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 )
    }
like image 889
Fay007 Avatar asked Dec 19 '16 10:12

Fay007


2 Answers

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.

like image 126
Nirav D Avatar answered Oct 24 '22 04:10

Nirav D


You can completely get rid of that cells only by filtering your dataSource array.

    var filtered = dataSource.filter { (item) -> Bool in
       item != "@"
    }

and use this filtered array instead of source.

like image 29
Ilia Avatar answered Oct 24 '22 05:10

Ilia