简体   繁体   English

如何使UICollectionView的某个部分中的所有项目浮动在滚动视图上?

[英]How to make all items in a section of a UICollectionView float over the scroll view?

I want the items of one section in a UICollectionView to remain stationary while the rest of the items inside the UICollectionView are being scrolled. 我希望UICollectionView中一个section的项目保持静止,而UICollectionView内部的其余项目正在滚动。

I tried to achieve this by setting Autolayout constraint that pin the items to the superview of the UICollectionView . 我试图通过设置将Autolayout固定到UICollectionView superview Autolayout constraint来实现此UICollectionView However, this does not seem to work because the constraints complain about UICollectionViewCell and the UICollectionView's superview not having a common ancestor. 但是,这似乎不起作用,因为constraints抱怨UICollectionViewCellUICollectionView's superview没有共同的祖先。

Is there any other way to achieve it? 还有其他方法可以实现吗?

Thanks to Ad-J's comment I was able to implement the solution. 感谢Ad-J的评论,我得以实现该解决方案。

I needed to override UICollectionViewFlowLayout and implement the following methods: 我需要重写UICollectionViewFlowLayout并实现以下方法:

override func prepareLayout() {
    super.prepareLayout()

    //fill layoutInfo of type [NSIndexPath:UICollectionViewLayoutAttributes]
    //with layoutAttributes you need in your layout

    if let cv = self.collectionView {
        for (indexPath, tileToFloat) in layoutInfo {
            if indexPath.section == 0 {
                var origin = tileToFloat.frame.origin
                origin.y += cv.contentOffset.y + cv.contentInset.top
                tileToFloat.frame = CGRect(origin: origin, size: tileToFloat.size)
            }
            tileToFloat.zIndex = 1
        }
    }
}

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
    return true
}

This will make all items in the first section stationary. 这将使第一部分中的所有项目保持静止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM