UICollectionView: A super simple example (iOS/Xcode)



In this example a UICollectionView will be created. Cells will be added using a BarButtonItem 'Add' button and they will be deleted by tapping on them.

Storyboard

The first step is to create a Single View Application with the name SimpleCollectionView.

Now open the Storyboard for the iPhone or iPad (whichever one you're going to be using to test the app).
  1. Drag out a Collection View Controller
  2. With the new view controller selected go to the Editor menu and select Embed In -> Navigation Controller
  3. Now drag a Bar Button Item to the top of the Collection View Controller
  4. Click to select the Bar Button Item and in the Attributes Inspector, change the Identifier  from Custom to Add
  5. Click the cell inside the Collection View
  6. In the Attributes Inspector  -> Collection Reusable View -> Identifier box type: Cell.
  7. Move the arrow that identifies the original View Controller as the initial view controller to the Navigation Controller
  8. Delete the original View Controller that was created with the project

ViewController .h file

If you've used the same naming convention as me, then this header file will be called SimpleCollectionViewViewController.h. If you haven't done this, then amend the following instructions accordingly.

First, amend the line that reads:
    
@interface SimpleCollectionViewViewController : UIViewController

so that it reads

@interface SimpleCollectionViewViewController : UICollectionViewController<UICollectionViewDataSource>
Second, return to the Storyboard and with the Collection View Controller selected go to the Identity Inspector and change the Custom Class to 'SimpleCollectionViewViewController'.

Now wire up the Add button to the .h file and specify an Action, which you need to call addCell.

ViewController .m file

Copy and paste this commented code to the implementation section of your .m file.

int numberOfCells=3; // Number of cells to begin with. This int will be incremented and decremented when cells are added and deleted.


-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView {
 
    return 1; // The number of sections we want
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
    numberOfItemsInSection:(NSInteger)section {
 
    return numberOfCells; // the number of cells we want
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
 
    UICollectionViewCell* cell =
    [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                              forIndexPath:indexPath]; // Create the cell from the storyboard cell
 
 
    cell.contentView.backgroundColor = [UIColor lightTextColor]; // Change the background colour of the cell
 
 
    return cell; // Return the cell
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self removeItemAtIndex:indexPath]; // a cell has been tapped call the method to delete it
}


// when the user selects a cell, and collectionView:didSelectItemAtIndexPath: is called, it then calls the following method
-(void)removeItemAtIndex:(NSIndexPath *)index {
 
 
        numberOfCells--; // update the data model by decrementing the int
     
        [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index.item inSection:0]]]; // update the interface
     
 
}

// When the user taps the Bar Button Item (Add) then the following method is called.
- (IBAction)addCell:(id)sender {
 
    numberOfCells++; // update the data model by incrementing the int
 
    [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:numberOfCells-1 inSection:0]]]; // update the interface
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


Build and Run

If successful you'll see something like this (but with slightly different colours if you kept with the defaults):

Tapping on any cell should delete that cell and tapping on the Add button should add a new one.

Update 1 March 2016: Swift version


import UIKit

class CollectionView: UICollectionViewController {
    
    var numberOfCells = 3 // Number of cells to begin with. This int will be incremented and decremented when cells are added and deleted.
    
    
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1 // The number of sections we want
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numberOfCells
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell // Create the cell from the storyboard cell
        
        cell.contentView.backgroundColor = UIColor.lightTextColor() // Change the background colour of the cell
        
        
        return cell; // Return the cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        
        self.removeItemAtIndex(indexPath) // a cell has been tapped call the method to delete it
        
    }
    
    
    // when the user selects a cell, and collectionView:didSelectItemAtIndexPath: is called, it then calls the following method
    func removeItemAtIndex(index:NSIndexPath) {
        
        numberOfCells-- // update the data model by decrementing the int
        self.collectionView?.deleteItemsAtIndexPaths([index]) // update the interface
        
    }
    
    // When the user taps the Bar Button Item (Add) then the following method is called.
    @IBAction func addCell(sender: UIBarButtonItem) {
        numberOfCells++; // update the data model by incrementing the int
        
        self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: numberOfCells-1 , inSection: 0)])  // update the interface
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
}
Endorse on Coderwall

Comments