Search code examples
uicollectionviewuicollectionviewcelluicollectionviewflowlayoutuicollectionviewdelegateflowlayout

Specify concrete cell sizes in UICollectionViewController?


I have a storyboard with UICollectionViewController with cell prototypes. The cell size is not specified directly and it causes random UI bugs like stretching cell animation. I want to set the size directly but I didn't found how to do that in xcode 10 (and the latest swift). How to solve this issue?

Note: I know about UICollectionViewDelegateFlowLayout existance but I don't know how to apply it to UICollectionViewController.


Solution

  • If you use UICollectionViewFlowLayout:

    1. Make your UICollectionViewController or UIViewController that contains UICollectionView instance to adopt UICollectionViewDelegateFlowLayout

      class MyAwesomeCollectionViewControler: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout 
      

      { ... }

    2. Implement the method below:

      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
          return CGSize(width: 100, height: 100) // Return desired size here}