Base UIViewController with UICollectionView

750 views Asked by At

I am having UIViewController which I want to use as a base controller for other view controllers. Base controller has a UICollectionView which has all the UICollectionViewCell prototype and some other stub views designed in storyboard.

All the child view controllers have one thing in common which is UICollectionView and has their own views in storyboard. I want to use the prototype cells designed in base view controller's collection view to populate child view controller's UICollectionView. I don't want to copy paste prototype cells from base controller's collection view to child controller collection view.

Base controller perform some actions on cell selection which are common to all child controllers. Child controller should be able to ask for any prototype cell from base controller, child will decide which cell to populate using cell identifiers.

I should be able to instantiate child controllers instead of base controller using their storyboard identifiers. I want to do maximum things in storyboard. How this can be accomplished? Please suggest or any other better approach.

I am programming in Objective-C.

1

There are 1 answers

1
dev gr On BEST ANSWER

After digging a lot I found that its not possible to re-use prototyped UICollectionViewCell so I ended up creating separate XIB for each collection view cell. This is what I did:

  1. Created XIBs for collection view cells.

  2. Wrote a base class BaseViewController which has a UICollectionView IBOutlet declared in its .h file. BaseViewController class confirms to UICollectionViewDelegate and UICollectionViewDataSource protocols.

    2.1 In BaseViewController viewDidLoad method, registered all cell XIBs to UICollectionView.

    2.2 Implemented delegate and data source methods which handle generic events. If needed child class can override those methods and perform specific tasks.

  3. Create child view controllers in storyboard which have UICollectionView. 3.1 Connected UICollectionView to super's UICollectionView IBOutlet defined in .h file.

Now all done! Now I could dequeue any cell that is registered in super or if child view controller wants some specific cells it can prototype them in its own UICollectionView in storyboard and do the job. Most of the times in my case didSelectItem was doing some generic operation in base class which were common to all child view controllers so I just dont implement it or if want to perform some other operations in addition to generic operations I implement the method and call super's implementation and after that do my stuff. All cell size and layout related methods are implemented by base view controller. Now I could create a new child view controller with collection view with minimal code and proper event handling.

Hope this helps someone. Thanks.