0

I have 3 collectionViews in one view controller. One has all cells of the same width and does not change. The other I would like to set the cell width in code using a constant. The last will calculate its cell's width based on the previous constant and other factors in a custom flow layout.

I tried

extension YourViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {



      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
             if collectionView == neededCollectionView {
             return CGSize(width: constantWidth, height: constHeight)
             } else {
                // here ignore all the others and tell them to get this size as usual
             }
        }

    }

but this seems to modify the width for all the collection views .. How do I get this two ignore the 2 collection views that have their size calculated somewhere else

user426132
  • 1,341
  • 4
  • 13
  • 28

2 Answers2

0

in this function you can't ignore, you need to return

CGSize

always.

try a break point and check if it gets into the else closure if so you could try to add this line,

 return CGSize(width: yourDefualtWidthConst, height:yourDefualtHeightconst)

or this

 return collectionView.itemSize 
Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • but the width is not a constant.. it needs to be calculated based on the item in the cell in one of the collection view 3 .. I suppose I coulf calculate it here instead on the layout subclass... – user426132 Sep 18 '18 at 21:39
  • https://developer.apple.com/documentation/uikit/uicollectionviewflowlayout/1617711-itemsize – Mohmmad S Sep 18 '18 at 21:42
  • @user426132 check the updated answer please and note me if it works good luck – Mohmmad S Sep 18 '18 at 21:50
0

You have Two options

FIRST OPTION : Return the estimatedItemSize of each CollectionViewCell

1. Get an IBOutlet Reference from each CollectionViewFlowLayout UICollectionViewFlowLayoutIBOutlet

@IBOutlet weak var firstFlowLayout: UICollectionViewFlowLayout!

2. Add UICollectionViewDelegateFlowLayout delegate in your viewController

3. Implement the delegate method

func collectionView( _ collectionView: UICollectionView,layoutcollectionViewLayout: UICollectionViewLayout,sizeForItemAtindexPath: IndexPath) -> CGSize {

         if collectionView.tag == 1 {
         return CGSize(width: constantWidth, height: constHeight)
         } elseIf collectionView.tag == 2 {
         return firstFlowLayout.estimatedItemSize
         }
}

SECOND OPTION : Adepter Design pattern

You can also use adapter class for each collectionview and each adapter has a different implementation to resolve this like this

https://stackoverflow.com/a/50920915/5233180

NOT : This implementation for TableView you can make it for collectionview

Magdy Zamel
  • 470
  • 5
  • 17