从滚动停止UICollectionView,使其显示所有单元格

问题描述 投票:0回答:1

我有一个集合视图,当它有10个或更少的项目时,它运行良好。每行有5个项目,因此最多10个项目有两行。但是,当我有10个以上的项目时,它将创建第3行,该行将被切除,并且收藏夹视图将开始滚动。当我尝试禁用滚动时,集合视图会切断最后一行。理想情况下,我希望有一个集合视图,无论我有多少行,它都会保持垂直扩展。有人能指出我实现这一目标的方向吗?

谢谢!

ios swift uicollectionview storyboard
1个回答
0
投票

1。对于动态高度更新

您可以为collectionView的contentSize添加观察者

   collectionView.addObserver(self, forKeyPath: "contentSize", options: [.new,.old], context: nil)

然后您可以重写此方法以检查collectionView中的contentSize更改

    override func observeValue(forKeyPath keyPath: String?,
                               of object: Any?,
                               change: [NSKeyValueChangeKey : Any]?,
                               context: UnsafeMutableRawPointer?) {

         if let obj = object as? UICollectionView, obj == self.collectionView && keyPath == "contentSize" {
            if let oldVal = change?[NSKeyValueChangeKey.oldKey] as? CGSize, let newValue = change?[NSKeyValueChangeKey.newKey] as? CGSize,oldVal.height == newValue.height  {
                return
            }

            let contentHeight = self.collectionView.contentSize.height
            //You can update the height constraint or you can manually update the height of collection view. 

            self.heightConstraintCV.constant = contentHeight 
        }
        UIView.animate(withDuration: 0.1) {
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }

2。一种简单的方法是手动计算高度。如果您确定每一行都有5个元素。

height = (numberOfRows * heightOfEachRow)

3。直接将contentSizeHeight设置为collectionView的高度

height = collectionView.contentSize.height

© www.soinside.com 2019 - 2024. All rights reserved.