Specify concrete cell sizes in UICollectionViewController?

41 views Asked by At

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.

2

There are 2 answers

2
fewlinesofcode On BEST ANSWER

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}
    
0
Vyachaslav Gerchicov On

Figured out that there are 2 kinds of layout available - "flow" and "custom" (these names are displayed in interface builder).

In short if you plan to use UICollectionViewDelegateFlowLayout and its simple method "size for item" then you should choose "flow"