-1

I'm struggling with resizing collection view.

Currently I'm having a flow layout method that counts size:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let cell = collectionView.cellForItem(at: indexPath) {
            let pokemonCell = cell as! PokemonCell
            pokemonCell.setNeedsDisplay()
        }
        return CGSize(width: 150, height: collectionView.bounds.size.height)
    }

And also two methods for resizing on rotation:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    guard let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }
    flowLayout.invalidateLayout()
    self.collectionView.reloadData()
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    collectionView.frame = self.view.bounds
    self.collectionView.reloadData()

}

Cell content is centered in container. When I change layout, cell content starts jumping. Some of them reposition themselves, some remain on y position of previous layout. Sometimes content gets correct positionig and than goes back wile scrolling.

screenshot

1 Answers1

1

try https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617728-invalidatelayout

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    collectionView.collectionViewLayout.invalidateLayout()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    collectionView.frame = self.view.bounds
}

invalidateLayout invalidates the layout of the collection view. But this method does not force an immediate update. It works something like UIView setNeedsLayout.

Don't call reloadData in layout's methods.

Also check the answers: UICollectionView Invalidate Layout On Bounds Changes and Swift: How to refresh UICollectionView layout after rotation of the device