0

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.

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49

2 Answers2

0

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"

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49
0

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}
    
fewlinesofcode
  • 3,007
  • 1
  • 13
  • 30
  • Sorry but in my case I have code which uses "custom" layout. So how to deal with it? Or maybe don't you know how to jump from "custom" to "flow"? – Vyachaslav Gerchicov Oct 10 '18 at 07:43
  • @Vyachaslav Gerchicov, in case of custom layout you must override the `func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?`. `UICollectionViewLayoutAttributes` object has `frame` property. This is where you determine the size. For further reading please see [uicollectionviewlayoutattributes](https://developer.apple.com/documentation/uikit/uicollectionviewlayoutattributes) and [uicollectionviewlayou](https://developer.apple.com/documentation/uikit/uicollectionviewlayout) documentation. – fewlinesofcode Oct 10 '18 at 07:49