Custom cell width for one collectionView

时间:2018-09-18 20:23:34

标签: ios uicollectionview

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

2 个答案:

答案 0 :(得分:0)

在此功能中,您不能忽略, 您需要返回

  

CGSize

总是。

尝试一个断点,并检查是否进入else闭包 您可以尝试添加此行,

 return CGSize(width: yourDefualtWidthConst, height:yourDefualtHeightconst)

或此

 return collectionView.itemSize 

答案 1 :(得分:0)

您有两个选择

  

第一选项:返回每个CollectionViewCell的EstimatedItemSize

1。。从每个CollectionViewFlowLayout获取IBOutlet参考。 UICollectionViewFlowLayoutIBOutlet

@IBOutlet weak var firstFlowLayout: UICollectionViewFlowLayout!

2。。在您的viewController中添加UICollectionViewDelegateFlowLayout委托

3。。实现委托方法

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
         }
}
  

第二个选择:Adepter设计模式

您还可以为每个collectionview使用适配器类,并且每个适配器都有不同的实现来解决此问题

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

:对于TableView的此实现,您可以将其用于collectionview