Fudgey
Fudgey

Reputation: 3833

Looping through CollectionView Cells in Swift

I'm wondering how to loop through all of my CollectionView Cells that currently visible.

In Objective C, I would achieve this concept seen below:

for(UICollectionView *cell in collectionView.visibleCells){

}

I've tried changing this into swift:

for cell:MyCollectionViewCell in self.collectionView.visibleCells() as cell:MyCollectionViewCell {

}

However I get the following error:

Type 'MyCollectionViewCell' does not conform to protocol 'SequenceType'

How do I loop through all my CollectionViewCells

Upvotes: 13

Views: 23886

Answers (3)

saneryee
saneryee

Reputation: 3405

In Swift 5:

There are five cells in section 0. Set each cells' backgroundcolor.

for row in 0..<collectionView.numberOfItems(inSection: 0){

            let indexPath = NSIndexPath(row:row, section:0)

            let cell:UICollectionViewCell = collectionView.cellForItem(at: indexPath as IndexPath) ?? cell

            switch row {
            case 0:
                cell.backgroundColor = .red
            case 1:
                cell.backgroundColor = .green
            case 2:
                cell.backgroundColor = .blue
            case 3:
                cell.backgroundColor = .yellow

            default:
                cell.backgroundColor = .white
            }
        }

Upvotes: 4

IsPha
IsPha

Reputation: 419

Im using this code , to loop through all table view cells , even not visible ones , you can use it is applied to collection views for sure ,

check my answer here :

https://stackoverflow.com/a/32626614/2715840

Upvotes: 1

Nate Cook
Nate Cook

Reputation: 93286

They way you're using as in that loop is trying to cast the array of visible cells to a single collection view cell. You want to cast to an array:

for cell in cv.visibleCells() as [UICollectionViewCell] {
    // do something        
}

or perhaps if you only have MyCollectionViewCell instances, this will work:

for cell in cv.visibleCells() as [MyCollectionViewCell] {
    // do something 
}

Upvotes: 33

Related Questions