Search code examples
swifttimerupdatescompletion

Variables are not updated in timer completion block


Here is the scenario:

I want to scroll(or shake) a horizontal collectionView after a page showing up so user could see it scrolling...

I do it with no problem 3 sec after page pops up but I don't want it to do the dance when user reach the collectionView before 2 sec & scrolls it itself.

So here is my solution for it:

   var collectionDidScroll = false

   func scrollViewDidScroll(_ scrollView: UIScrollView) {
        collectionDidScroll = true
   }

   override func awakeFromNib() {
        super.awakeFromNib()
        Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(showScrollTutorial), userInfo: nil, repeats: false)
   }

   @objc func showScrollTutorial() {
        if !collectionDidScroll {
            collectionView.shakeCells()
        }
   }

The Problem:

The "collectionDidScroll" is update just fine in class, but in timer completion its always false! It means "collectionDidScroll" is not updating in completion & it has its launch time value.

Notice:

My class is a subclass of UICollectionViewCell

I even tried dispatchQueue with timer & timer with completion block but the results are the same


Solution

  • Problem Solved!

    I placed 'showScrollTutorial()' function contents inside a 'DispatchQueue' to force it to run in main thread, now it works like a charm!

    Thanks for everyone.