Ninja
Ninja

Reputation: 358

Interface does not update in willTransition(to: , with: ) without DispatchQueue.main.async

I am trying to handle a device rotation, and (during the rotation process) make some "efforts" to scroll my collectionView to specified item . So if I do it in DispatchQueue.main.async() everything updates.

 override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{ 
    DispatchQueue.main.async {    
    let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
    self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
  }
}

But I do it just in willTransition func without involving DispatchQueue.main.async() interface doest not updates, nothing happens.

 override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{  
    let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
    self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}

Why? What it it's(DispatchQueue in the context of willTrasition func) charm?

Upvotes: 0

Views: 176

Answers (1)

rmaddy
rmaddy

Reputation: 318934

Try using the coordinator so you scroll the collection view as part of the rotation.

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
    coordinator.animate(alongsideTransition: { (context) in
        let indexPath = IndexPath(item: self.pageControl.currentPage, section: 0)
        self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }, completion: nil)
}

The most likely reason your code fails when not using DispatchQueue.main.async is that you end up trying to scroll too soon and when you do use it, the scrolling is delayed long enough to be effective.

Upvotes: 1

Related Questions