Search code examples
iosobjective-cstoryboarduicollectionviewuicollectionviewcell

Reuse single UICollectionViewCell in multiple collection views


I have multiple collection views that need to use the same prototype cells. Right now, I'm duplicating the prototype cells in each collection view in storyboard (as seen below). This is not very DRY and becomes a pain when making storyboard changes to the cells.

Is it possible to define the cell in one place in storyboard?

enter image description here

Alternatively I tried using only 1 collection view, but I couldn't get the 3 column layout where cells stack and scroll vertically, so I moved to 3 collections views.


Solution

  • Yes this is possible. I never design cells (UITableView or UICollectionView cells ) in the storyboard. Chances are, you'll need to reuse them as is the case here.

    To begin with, create a new view (File > New > File) and select the View option from the User Interface section. It doesn’t matter which device family you choose, so give it a name (I’m calling mine NibCell). It will open up in the canvas – the first job is to delete the existing view, and drag in a Collection View Cell from the Object Browser.

    You would also create a subclass of UICollectionViewCell class and set it to the class of the xib file in interface builder. Once you have created the xib and wired up the elements to the custom class - you need to register it like so in your class that has the UICollectionView in it (don't forget to import it the custom cell class first!)

    UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
    

    And you would use it like so:

    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *cellIdentifier = @"cvCell";
    
        CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        //Setup the cell for use 
        return cell;
    
    }
    

    And thats generally all there is to it. Hope this helps!