11

So I have a UICollectionView that I want to use to display multiple UICollectionViewCells and different headers depending on the state the user is in. The problem is I can't seem to register multiple UICollectionResuableView (header) views within the storyboard. If I try to register one as a footer and use it as a header the app crashes. I also do not see anywhere in the storyboard to declare the number of sections, which would alleviate the problem. For now I'm having to use multiple UICollectionViews and hide/unhide the collectionview I want to display based on the header I need. Is there a better way to do this, or a way to register multiple header views in the same UICollectionView within the storyboard?

CA Bearsfan
  • 454
  • 4
  • 20

1 Answers1

13

You cannot register more than one header in a UICollectionView in a storyboard, but you can register an arbitrary number of them in code. You should create however many headers as you want in nib files (One nib per header, with the header as the top level object), and register them with your collection view instance in viewDidLoad.

You would do this with the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method.

Charles A.
  • 10,685
  • 1
  • 42
  • 39
  • 1
    I had been trying the registerClass: method, much cleaner approach. Would still be nice to be able to set this value on the collectionview inside the storyboard though. – CA Bearsfan Oct 03 '15 at 21:52
  • Which register method you use depends on if you want to implement your UI in a NIB or in code I suppose. I typically find myself using the NIB approach. – Charles A. Oct 04 '15 at 06:13
  • 4
    What a ridiculous exercise in frustration that was. Guess I should have just put it in a separate nib to begin with. – TylerJames Nov 25 '16 at 22:25
  • @AndrewKinnie I still use NIB files pretty regularly so I can share common cells across different view controllers without having to copy/paste things all around my Storyboards. Easier to update designs that way, but it is an annoying limitation. I doubt it'll get much attention now that there is SwiftUI. – Charles A. Apr 23 '20 at 04:43