【问题标题】:Stop UICollectionView From Scrolling and Make it Show All Cells停止 UICollectionView 滚动并使其显示所有单元格
【发布时间】:2020-05-15 14:35:35
【问题描述】:

我有一个集合视图,当它有 10 个或更少的项目时,它可以正常工作。每行有 5 个项目,因此最多 10 个项目有两行。但是,当我有超过 10 个项目时,它会创建一个被截断的第三行,并且集合视图开始滚动。当我尝试禁用滚动时,集合视图会切断最后一行。理想情况下,我希望有一个集合视图,无论我有多少行,它都会保持垂直扩展。任何人都可以为我指明实现这一目标的方向吗?

谢谢!

【问题讨论】:

    标签: ios swift uicollectionview storyboard


    【解决方案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

    【讨论】:

    • 集合视图单元格在布局后将是静态的,因为用户永远不会看到它发生变化,所以我正在寻找一种在打开视图时布局它的方法。这对它有用吗?
    • 在这种情况下,您可以直接获取 contensize,例如 collectionView.contentSize,而不是观察它。然后将高度设置为collectionView的高度
    • 另一种方法是,如果你知道你的单元格的高度,你可以计算(no. of cells) * height
    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 2017-02-21
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多