首页 文章

使用FlowLayout和可变数量的单元格自行调整UICollectionView的大小

提问于
浏览
1

请注意,这是关于自行调整UICollectionViewCell大小的问题 NOT .

是否有可能创建自定义UICollectionView(UICollectionViewFlowLayout)的大小取决于其中的单元格?

我有一个包含可变数量单元格的集合视图 . 我想约束集合视图的宽度,然后允许它根据单元格的数量垂直扩展 .

这个问题类似于这个问题CollectionView dynamic height with Swift 3 in iOS但我每行有多个单元格 .

奖励点,如果仍然可以在集合视图中使用自调整大小单元格,但是如果集合视图委托提供单元格大小则可以 .

2 回答

  • 1

    我没有足够的声誉来评论,但我认为this is the answer你正在寻找 . 代码如下:

    class DynamicCollectionView: UICollectionView {
         override func layoutSubviews() {
             super.layoutSubviews()
             if bounds.size != intrinsicContentSize() {
                 invalidateIntrinsicContentSize()
             }
         }
    
         override func intrinsicContentSize() -> CGSize {
             return self.contentSize
         }
     }
    
  • 0

    @Michal Gorzalczany的回答让我得到了这个答案(针对我的具体案例):

    • 子类UICollectionView
    class DynamicCollectionView : UICollectionView {
    
        weak var layoutResp : LayoutResponder?
    
        override func invalidateIntrinsicContentSize() {
            super.invalidateIntrinsicContentSize()
            self.layoutResp?.updateLayout()
        }
    
        override var intrinsicContentSize : CGSize {
            return self.contentSize
        }
    
        override var contentSize: CGSize {
            get { return super.contentSize }
    
            set {
                super.contentSize = newValue
                self.invalidateIntrinsicContentSize()
            }
        }
    }
    
    • Protocol LayoutResponder 应该被视图采用,该视图处理高级别的集合视图布局(我有一个相对复杂的布局) .
    protocol LayoutResponder : class {
        func updateLayout()
    }
    
    
    extension RespView : LayoutResponder {
        func updateLayout() {
            self.layoutResp?.setNeedsLayout()
            self.layoutResp?.layoutIfNeeded()
        }
    }
    

    在我的情况下,我实际上甚至更进一步向前推进 updateLayout() .

    我想对于更简单的布局,你可以完全跳过第2步 .

    这在我看来有点“hacky”所以如果有人有更好的方法我会很感激,如果你分享 .

相关问题