首页 > 解决方案 > 一个 collectionView 的自定义单元格宽度

问题描述

我在一个视图控制器中有 3 个集合视图。一个具有相同宽度的所有单元格并且不会改变。另一个我想使用常量在代码中设置单元格宽度。最后一个将根据自定义流布局中的先前常量和其他因素计算其单元格的宽度。

我试过了

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

    }

但这似乎修改了所有集合视图的宽度.. 我如何让这两个忽略在其他地方计算大小的 2 个集合视图

标签: iosuicollectionview

解决方案


你有两个选择

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

1. 从每个 CollectionViewFlowLayout 中获取一个 IBOutlet Reference 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 设计模式

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

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

NOT : TableView 的这个实现你可以让它用于collectionview


推荐阅读