6

i tried to implement rotation adjustments so in tutorial author was using invalidatelayout function before setting new preferences. but all actually works without invalidateLayout, and yet i tried it in another circumstance before and got the same "nothing" output.

   override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    collectionView.collectionViewLayout.invalidateLayout()

    let indexPath = IndexPath(item: pageControl.currentPage, section: 0)
    //scroll to indexPath after the rotation is going
    DispatchQueue.main.async {
        self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        self.collectionView.reloadData()
    }

}

So why do we need invalidateLayout? (and i read docs but it seems that this function is somewhat..it seems do nothing... i don't know...maybe redundant?)

Ninja
  • 309
  • 7
  • 26
  • 1
    Why do we need invalidate layout? Because we might need to update the layout of our collection view. – John Snow Mar 14 '18 at 14:28
  • 1
    It is different from reload data because it does not recreate the cells and such, it just updates the layout. If you data doesn't change, and you just want to update the layout, you should call invalidate layout. – John Snow Mar 14 '18 at 14:30
  • @John Snow then why do we need layoutIfNeeded()? – Ninja Mar 14 '18 at 14:33
  • 6
    If you call invalidateLayout() your layout is updated as soon as the next layout update cycle occurs. If you call invalidateLayout() and then layoutIfNeeded() the layout will be updated immediately. If you just call layoutIfNeeded() and the layout is still valid, nothing will happen. – John Snow Mar 14 '18 at 14:36
  • 1
    In other words they serve two different but related purposes. – John Snow Mar 14 '18 at 14:37

0 Answers0