UICollectionViewCell具有2列网格和动态高度

时间:2020-04-23 19:36:36

标签: ios swift uicollectionview uicollectionviewcell

我正在尝试使用2列但动态高度的集合视图。 我已经使用了自动版式,并为单元格设置了必需的约束

通过这种方式,我可以计算动态高度,但是其列网格会失败。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MenuListCollectionViewCell
       cell.frame.size.width = collectionView.frame.width/2
    cell.menuList = self.menuList[indexPath.row]
    let resizing = cell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
       return resizing
}

这就是我想要的样子

3 个答案:

答案 0 :(得分:2)

不确定“列网格失败”是什么意思。

无论如何,您需要编写一个自定义集合视图布局。默认的(UICollectionViewFlowLayout)允许您通过提供sizeForItemAt来更改单元格的高度,但这不会改变总是将单元格排列在相同高度的行中的布局行为(最高的单元格。

如果我理解正确,那么您只想要this raywenderlich tutorial的相同布局。

基本上:

  1. 创建UICollectionViewLayout的子类来实现其方法:
  2. collectionViewContentSize:返回集合视图内容的宽度和高度
  3. prepare:您可以在其中计算像元大小和 collectionView内容
  4. layoutAttributesForElements:您在哪里 返回给定的UICollectionViewLayoutAttributes数组 rect
  5. layoutAttributesForItem:您返回的同类 属性,这一次是针对商品的
  6. 将此类的对象分配给集合视图布局属性

答案 1 :(得分:0)

您可以使用此

这段代码是用某种方式编写的,您可以更改节的inset或minimumInteritemSpacing并使用此参数进行计算和调整大小

您可以使用此代码或从Github下载项目

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let numberofItem: CGFloat = 2

        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout

        let collectionViewWidth = self.collectionView.bounds.width

        let extraSpace = (numberofItem - 1) * flowLayout.minimumInteritemSpacing

        let inset = flowLayout.sectionInset.right + flowLayout.sectionInset.left

        let width = Int((collectionViewWidth - extraSpace - inset) / numberofItem)

        return CGSize(width: width, height: width)
    }

答案 2 :(得分:0)

通过执行以下操作,我能够达到您想要的结果。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 20
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (self.view.frame.size.width/2 - 5), height: 100)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = customCollectionView.dequeueReusableCell(withReuseIdentifier: "test", for: indexPath)

    cell.layer.backgroundColor = UIColor.red.cgColor

    return cell
}

确保已实现所有正确的委托

  • UICollectionViewDelegate
  • UICollectionViewDatasource
  • UICollectionViewDelegateFlowLayout

看到高度的地方:按照您在问题中指定的高度,将其设置为您想要的高度。

键:确保在情节提要中将收藏夹视图的estimate size设置为“无”->否则代码将无法正常工作

enter image description here

相关问题