我有一个集合视图,当它有10个或更少的项目时,它运行良好。每行有5个项目,因此最多10个项目有两行。但是,当我有10个以上的项目时,它将创建一个第3行,该行将被切断,并且收藏夹视图将开始滚动。当我尝试禁用滚动时,集合视图会切断最后一行。理想情况下,我想要一个集合视图,无论我有多少行,它都将保持垂直扩展。有人能指出我实现这一目标的方向吗?
谢谢!
答案 0 :(得分:1)
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