如何根据 swift 中的行数调整 UICollectionView contentSize.height

How to adjust UICollectionView contentSize.height based on number of rows in swift

如果有人能在这里提出一些想法,我将不胜感激。几个星期以来我一直在努力解决这个问题(不是开玩笑)。

我有一个使用 collectionView 的 "to do list",我在其中隐藏已完成的行并将它们移动到列表的末尾。然后,如果需要,我可以使用按钮取消隐藏这些项目。 collectionView 看起来与每行一个项目(单元格)的 tableView 完全一样。

当项目被隐藏时,collectionView 在底部有很多空滚动 space 而不是自动删除隐藏行使用的 space,因为它们在技术上仍然存在。

我正在尝试剪切空的 space,这样 collectionView 的高度将等于 cells/rows 可见部分的高度。

override func viewDidAppear(animated: Bool) {

if isCellHidden { //checking if cells are hidden 
var heightOfSection0 = 95 + (42 * self.collectionView.numberOfItemsInSection(0))
println(self.collectionView.contentSize.heigh) //returns 2350
self.collectionView.contentSize.height = CGFloat(heightOfSection0)
println(heightOfSection0) //returns 1019
println(self.collectionView.contentSize.heigh) //returns 1019.0 which is correct but as soon as I scroll down it resets to it's original size (2350) and let's me scroll through that empty space...
}}

如果我尝试在设置后立即读取 collectionView 高度,它会显示正确的值,但一旦我尝试向下滚动,它就会重置回原始高度。我也试过禁用自动布局,但没有什么区别

您不应该直接管理 contentSize - return 适当数量的项目,而是从 collectionView(_:numberOfItemsInSection:) 中显示(即不计算您的 "hidden" 单元格)。

更改 UI 中 viewDidAppear() 的东西在理论上是一个很好的地方。但是,此时您不能确定自动布局是否已对您正在操作的子视图进行操作。

您可以检查它何时拥有以及何时可以安全地操作框架,方法是将它子类化并覆盖 layoutSubviews()

我在这里遇到了类似的问题:

您可以使用 sizeForItemAtIndexPath: 更改集合视图单元格的大小。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var numberOfCellInRow : Int = 3
    var padding : Int = 5
    var collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding)
    return CGSize(width: collectionCellWidth , height: collectionCellWidth)
}