6

I have a custom UICollectionViewLayout that makes use of the self-sizing mechanism in iOS 8. My UICollectionViewCell's implement preferredLayoutAttributesFittingAttributes to return their preferred size, calculated using auto-layout. This works fine.

However, I was expecting preferredLayoutAttributesFittingAttributes to also work for supplementary views, but it is never called. It is defined on UICollectionReusableView after all.

If this mechanism is only for cells, what is the correct way to use auto-layout to size supplementary views in a custom UICollectionViewLayout?

AndrewC
  • 401
  • 4
  • 19

1 Answers1

3

preferredLayoutAttributesFittingAttributes will be called on supplementary views so long as they conform to the following requirements in your UICollectionViewLayout subclass (as far as I can tell!):

  1. The supplementary view is laid out with a non-zero frame in prepareLayout
  2. Layout attributes are provided for the supplementary view in layoutAttributesForSupplementaryViewOfKind:atIndexPath:
  3. The supplementary view is visible according to layoutAttributesForElementsInRect:
  4. Lastly, ensure the elementKind matches up in your CollectionView's collectionView:viewForSupplementaryElementOfKind:atIndexPath: when the supplementary view is dequeued via dequeueReusableSupplementaryViewOfKind:forIndexPath:

In summary: UICollectionViewLayout is a wicked beast but if tamed should be calling your supplementary view's preferredLayoutAttributesFittingAttributes.

Warpling
  • 2,024
  • 2
  • 22
  • 38
  • But the truth, surely, is that self-sizing cells don't really work very well, so one can't be surprised if self-sizing supplementary views don't work either. – matt Aug 31 '16 at 02:25
  • They don't work very well but that doesn't mean the method shouldn't get called ;) – Warpling Aug 31 '16 at 03:53