UICollectionView挑战:在最后一个单元格上设置高度以适应可用空间

时间:2017-09-07 12:27:50

标签: ios swift uicollectionview

你能解决以下问题:我有一个带有固定数量的CollectionView单元的UICollectionView - 但是设备的高度发生变化,我必须动态计算最后一个(buttom)单元格。

------
I: Cell 1
------
I: Cell 2
------
I: Cell 3, This cell has a dynamic hight
I
------

我尝试了以下内容:

注意:let view = self.cells[indexPath.row]是我添加到cellForItemAt

中的UICollectionView contextView的UIView的固定列表

此外,代码位于实现UICollectionViewDelegateFlowLayout

的类中
self.collectionView?.isScrollEnabled = false

    var totalHight: CGFloat = 0

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

        let view = self.cells[indexPath.row]

        self.totalHight = self.totalHight + view.frame.size.height

        if (self.totalHight > self.frame.size.height){
            let diff = self.totalHight - self.frame.size.height
            let height = (view.frame.size.height - diff)

            view.frame.size = CGSize(width: self.frame.size.width,
                                     height: height)
            self.totalHight = 0
            return view.frame.size
        }else{
            return CGSize(width: self.frame.size.width, height: view.frame.size.height)
        }
}

1 个答案:

答案 0 :(得分:3)

我无法判断您尝试过的代码是在视图控制器中还是在自定义布局中。结果是什么?

可以使用自定义UICollectionViewLayout实例完成。您可以通过子类化UICollectionViewFlowLayout并覆盖

来实现
collectionView:layout:sizeForItemAtIndexPath:

然后您可以查看屏幕上的剩余空间。如果内容最终超出可用空间,则可能会出现问题。

您可能会看到一种方法是获取前一个单元格的布局属性,这将为您提供框架,如下所示:

let previousIndexPath = IndexPath(row: indexPath.row - 1, section: indexPath.section)
let attribs = layoutAttributesForItem(at: previousIndexPath)
let previousFrame = attribs.frame

let availableHeight = totalHeight - previousFrame.size.height
return CGSize(width: previousFrame.width, height: availableHeight)

在此处查看更多信息:

https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html

https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617797-layoutattributesforitem

编辑:顺便说一句,听起来好像使用UIStackView和autolayout约束会让这件事变得更容易,因为你的内容是静态的,不会滚动。< / p>