0

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?

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30
Damnum
  • 1,839
  • 16
  • 35
  • Use another view.. Don't add it in collection view. – Alok Rao May 31 '16 at 12:17
  • The problem is the user needs to be able to drag and drop items from one section to another. Introducing another view makes it much harder to do so – Damnum May 31 '16 at 12:35
  • Did you try using header for collection view? A floating header can be implemented as mentioned [here](http://stackoverflow.com/questions/13511733/how-to-make-supplementary-view-float-in-uicollectionview-as-section-headers-do-i) – dispatchMain May 31 '16 at 12:37
  • This approach seems to only work for supplementary views (headers and footers) but I need the actual UICollectionView items to remain stationary – Damnum May 31 '16 at 12:43

1 Answers1

0

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.

Damnum
  • 1,839
  • 16
  • 35