Damnum Damnum - 6 months ago 10
iOS Question

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.

I tried to achieve this by setting
Autolayout
constraint
that pin the items to the
superview
of the
UICollectionView
. However, this does not seem to work because the
constraints
complain about
UICollectionViewCell
and the
UICollectionView's
superview
not having a common ancestor.

Is there any other way to achieve it?

Answer

Thanks to Ad-J's comment I was able to implement the solution.

I needed to override UICollectionViewFlowLayout and implement the following methods:

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.