title: Only one sticky header in UICollectionView
body: <p>I'm trying to implement a single sticky header in a <code>UICollectionView</code>. </p>
  
  <p>My sticky header behavior is a bit different than the usual one you can see e.g. in <code>UITableView</code>. I have 3 headers in the collection view and <strong>I want only one of them to be sticky</strong> and stick to the top when the content is scrolled.</p>
  
  <p>My code works pretty well. However, when I scroll down, the sticky header disappears suddenly at some point. Scrolling back makes the header appear again. What am I doing wrong? </p>
  
  <p>I am attaching a implementation of my custom layout. It's a subclass of <code>UICollectionViewFlowLayout</code>.</p>
  
  <pre><code>@implementation CustomFlowLayout
  
  
  - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
  {
      NSMutableArray *attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
      CGPoint const contentOffset = self.collectionView.contentOffset;
  
      for (UICollectionViewLayoutAttributes *layoutAttributes in attributes)
      {
          // Adjust the sticky header frame.
          if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader] &amp;&amp;
              layoutAttributes.indexPath.section == SectionWithStickyHeadeIndex)
          {
              NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:SectionWithStickyHeadeIndex];
              NSIndexPath *firstObjectIndexPath = [NSIndexPath indexPathForItem:0
                                                                      inSection:SectionWithStickyHeadeIndex];
              UICollectionViewLayoutAttributes *firstObjectAttrs;
  
              if (numberOfItemsInSection &gt; 0)
              {
                  firstObjectAttrs = [self layoutAttributesForItemAtIndexPath:firstObjectIndexPath];
              }
              else
              {
                  firstObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                          atIndexPath:firstObjectIndexPath];
              }
  
              CGPoint origin = layoutAttributes.frame.origin;
  
              // Adjust the header origin so it sticks to the top.
              origin.y = MAX(contentOffset.y + self.collectionView.contentInset.top,
                             CGRectGetMinY(firstObjectAttrs.frame) - CGRectGetHeight(layoutAttributes.frame));
  
              layoutAttributes.zIndex = CGFLOAT_MAX;
              layoutAttributes.frame = (CGRect)
              {
                  .origin = origin,
                  .size = layoutAttributes.frame.size
              };
  
              break;
          }
      }
  
      return attributes;
  }
  
  
  - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBound
  {
      return YES;
  }
  
  
  @end
  </code></pre>