我试图用2列但动态高度的集合视图,我已经使用了Autolayout,并给Cell所需的约束。
通过这种方式,我可以计算动态高度,但它的列网格失败。
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
}
这是我想要的样子
不知道你说的 "其列网格失败 "是什么意思。
总之,你需要写一个自定义的集合视图布局。默认的(UICollectionViewFlowLayout)允许你改变单元格的高度,通过提供的 sizeForItemAt
但这不会改变布局的行为,即总是将单元格排列在相同高度的行中(最高单元格的高度)。
如果我的理解没错,您只是想让您的单元格的布局与我们的 这个雷文德利希教程.
基本上。
UICollectionViewLayout
实现它的方法。collectionViewContentSize
:返回集合视图内容的宽度和高度。prepare
在这里你可以计算单元格和collectionView内容的大小。layoutAttributesForElements
: 其中你返回一个数组 UICollectionViewLayoutAttributes
在给定的rectlayoutAttributesForItem
: 返回同样的属性,这次是针对一个项目的特定属性你可以用这个
这段代码是以某种方式写的,你可以改变部分插入或最小的InteritemSpacing,并计算和调整大小与此参数。
您可以使用这段代码或从以下网站下载项目 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)
}
我是通过做以下工作来达到你所期望的结果的。
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
}
确保你已经实施了所有正确的委托人
在你看到高度的地方:按照你在问题中指定的高度,把它变成你自己想要的高度。
关键:确保在你的故事板中你已经设置了 estimate size
的NONE -> 否则代码将无法正常工作。