If statement based on timer

Okay. I have a Timer in my ViewController.
I also have a collection view.

I want to run an if statement based on the timer that affects something in the collection view.

However when I put the statement in the collection view with the cell, it does not run, it’s as if the timer object is static.
I have tried putting the timer inside the collection view however this threw up an error about .Timer needing to be a top level object and not a local one.

Below is my code. Suggestions appreciated.

@objc func timerElapsed() {
        seconds -= 1
        timerLabel.text = "\(seconds)"
        if seconds <= 0 {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellImages.count

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! CollectionViewCell
        cell.yellowSquare.image = cellImages[indexPath.item]
        return cell


Do you have the timer call in your viewDidLoad?

Let us know.


Hello again my friend

Yes, I have the following in my viewDidLoad

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerElapsed), userInfo: nil, repeats: true)

Ok, I expect the problem is the dequing the cell when it reloads.

This StackExcahnge conversation has a solution for TableView, should be pretty easy to modify for a collection view.

Good luck!


Many thanks Mark. I’ll get to work.

Take Care