Introduction to UICollectionView in IOS 6 : Step by Step tutorial

Introduction to UICollectionView step by step tutorial / How to add UICollectionView to a project

This tutorial will help you to learn about UICollectionView. Apple introduced UICollectionView in iOS 6. It is one of the great breakthrough in User experience in iphone application development. Why i say that, it will help the developer to create a good and high Quality structured album like view with different layouts can be developed in a lightning fats. This UICollectionView can be used in both iphone and ipad application development. UICollectionView will help you to prepare a high Quality albums, Landing views with High Quality thumbnail images, Also help you to prepare a stamp Collection view.
It is one of the extended form of UITableView class which is available in our old iOS versions  and new iOS versions. UICollectionView and UITableView are shares a lot common design patterns but it’s API’s are kinda different.  Both UICollectionView and UITableView is used to present the related data to the users in a good way. Don’t get confused that it is the best way to replace UITableView with UICollectionView. Both have its own significance.

Advantages of UICollectionView

[box type =”info”]

1. UICollectionView is Flexible

2. UICollectionView is Extensible

3. UICollectionView is Configurable

[/box]

OverView of UICollectionView

Let’s get in to Overview of UICollectionView,It is basically a collection of different class such as UICollectionView, UICollectionViewCell, UICollectionViewLayout, UICollectionViewLayoutAttributes, UITouch, UINib, UICollectionReusableView.

In this UICollectionView each data node representation is encapsulate inside the UICollectionViewCell Instance. The UICollectionView class provides a scrollable container that holds a collection of cells. UICollectionViewLayout handles the layout representation in the UICollectionView. We can switch the layout of UICollectionView with the help UICollectionViewLayout instance. This will help us to get a very good dynamic behaviour for the UICollectionView.

The UICollectionViewLayout is not restricted to a particular type of layout, but it ships with a subclass, UICollectionViewFlowLayout, that has been designed for constructing both line and grid-based layouts.

Much like table views, a collection view interacts with the underlying data through a data source and responds to UI events with the help of a delegate.The layout class can manage the layout in a couple of ways – by setting global properties on cells or by means of delegation. The latter endows the layout class with finer grained control of the appearance of the UI.

 

 Methods Available in UICollectionView  

[box]

1. Initialising a UICollectionView

- (id)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{

//   Parameters
//    
//   frame
//   The frame rectangle for the UICollectionView, measured in points. The origin of the frame is   relative to the superview in which you plan to add it. This frame is passed to the superclass during initialization.
//     
//   layout
//   The layout object to use for organizing items. The UICollectionView stores a strong reference to the specified object. You may specify nil for this parameter.
//       
//   Return Value
//   An initialized UICollectionView object or nil if the object could not be created.

}

2.Configuring the UICollectionView

 

2.1 setting the UICollectionViewLayout property

collectionView.collectionViewLayout=  (UICollectionViewLayout *)......;
//or 
 [collectionView setCollectionViewLayout:(UICollectionViewLayout *)];
//any class instance can be used which is inherited from the UICollectionViewLayout.

2.2 setting the UICollectionView Layout : (setCollectionViewLayout:animated:)

- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated
//    Parameters
//    layout
//    The new layout object to use to organize the UICollectionView.
//    
//    animated
//    Specify YES if you want to animate changes from the current layout to the new layout specified by the layout parameter. Specify NO to make the change without animations.
//      
    }

usage of UICollectionView Layout

 [collectionView setCollectionViewLayout:(UICollectionViewLayout *) animated:(BOOL)];

2.3 UICollectionView delegate property

[collectionView setDelegate:id(uicollectionviewdelegate)];
//This will help you to set the delegate of the UICollectionView.

2.4 UICollectionView dataSource property

[collectionView setDataSource:id(UICollectionViewDataSource)];
//This will help you to set the datasource of UICollectionView.

2.5 UICollectionView backgroundView property

 [collectionView setBackgroundView:(UIView *)];
//This will help you to set the backgroundView property of UICollectionView

3.Creating UICollectionViewCells

 

3.1 RegisterClass forCellWithReuseIdentifier in UICollectionViewCell

- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier{
//    Parameters
//    cellClass
//    The class of a cell that you want to use in the UICollectionView.
//    
//    identifier
//    The reuse identifier to associate with the specified class. This parameter must not be nil and must not be an empty string.
//    
}

3.2 RegisterNib forCellWithReuseIdentifier in UICollectionView

- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier{
//    Parameters
//    nib
//    The nib object containing the cell object. The nib file must contain only one top-level object and that object must be of the type UICollectionViewCell.
//    
//    identifier
//    The reuse identifier to associate with the specified nib file. This parameter must not be nil and must not be an empty string.
//    
}

3.4 registerClass forSupplementaryViewOfKind withReuseIdentifier in UICollectionView

- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier{

}

3.5 dequeueReusableSupplementaryViewOfKind withReuseIdentifier forIndexPath in UICollectionVIew

- (id)dequeueReusableSupplementaryViewOfKind:(NSString*)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath*)indexPath{

//Parameters
//elementKind
//The kind of supplementary view to retrieve. This value is defined by the layout object. This parameter must not be nil.

//identifier
//The reuse identifier for the specified view. This parameter must not be nil.

//indexPath
//The index path specifying the location of the supplementary view in the UICollectionView. The data source receives this information when it is asked for the view and should just pass it along. This method uses the information to perform additional configuration based on the view’s position in the collection view.

//Return Value
//A valid UICollectionReusableView object.
}

4. Reloading Content in UICollectionView

 

4.1 reloadData in UICollectionView

[collectionView reloadData]; 

//This will reload data inside the UICollectionView.

4.2 reloadSections in the UICollectionView

//This will help you to reload the Data in the specific section inside the UICollectionView. 

- (void)reloadSections:(NSIndexSet *)sections
//this can be used like this in UICollectionView.
[collectionView reloadSections:1];

4.3 reloadItemsAtIndexPaths in UICollectionView

//This will help you to reload data at indexpath of UICollectionView. The method will be look like this
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths

5. Getting the State of the UICollectionView

 

5.1 numberOfSections in the UICollectionView

//Here you need to tell how many sections do you have for the UICollectionView 
 - (NSInteger)numberOfSections{

   return 5;
}

5.2 numberOfItemsInSection in the UICollectionView.

- (NSInteger)numberOfItemsInSection:(NSInteger)section{

   return 5;
}

5.3 visibleCells in the UICollectionView

//This will return a array of UICollectionViewCells  in the UICollectionView.
- (NSArray *)visibleCells

6. Inserting, Moving, and Deleting Items in UICollectionView

 

6.1 insertItemsAtIndexPaths in UICollectionView

//This will help you to insert a cell at the indexpath of the UICollectionView. 
- (void)insertItemsAtIndexPaths:(NSArray *)indexPaths

6.2 moveItemAtIndexPath:toIndexPath in UICollectionView

- (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath

6.3 deleteItemsAtIndexPaths in UICollectionView

- (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths

7.Inserting, Moving, and Deleting Sections in the UICollectionView

7.1 insertSections: in the UICollectionView

7.2 moveSection:toSection: in the UICollectionView

7.3 deleteSections: in the UICollectionView

8. Managing the Selection in UICollectionView

8.1 allowsSelection property in the UICollectionView

8.2 allowsMultipleSelection in the UICollectionView

8.3 indexPathsForSelectedItems in the UICollectionView

8.4 selectItemAtIndexPath:animated:scrollPosition: in the UICollectionView

8.4 deselectItemAtIndexPath:animated: in the UICollectionView

9.Locating Items in the UICollectionView

9.1 indexPathForItemAtPoint: in the UICollectionView

9.2 indexPathsForVisibleItems: in the UICollectionView

9.3 indexPathForCell: in the UICollectionView

9.4 cellForItemAtIndexPath: in the UICollectionView

10. Getting Layout Information in the UICollectionView

10.1 layoutAttributesForItemAtIndexPath: in the UICollectionView

10.2 layoutAttributesForSupplementaryElementOfKind:atIndexPath: in the UICollectionView

11.Scrolling an Item Into View in UICollectionView

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated

12.performBatchUpdates:completion: in UICollectionView
[/box]

Now Lets move to the Implementation of UICollectionView in Real World
Now lets get start a new project in Xcode and name it as UICollectionViewExample
UICollectionView Example

in this UICollectionView Example Project, i am only enabling orientation as portrait

UICollectionView Example 2

next need to add UICollectionView to the Xib file.

UICollectionView xib file image

Now need to create a IBOutlet of UICollectionView and name it as collectionViewPack;

#import "SSNViewController.h"

@interface SSNViewController (){

    IBOutlet UICollectionView *collectionViewPack;
}

@end

Now we need to wire the collectionView to the UICollectionView which is added in the Xib file. And also wire up the UICollectionView datasource and UICollectionView delegate to the FilesOwner.
Now its the time to crack some more code in the implementation file.

#import "SSNViewController.h"
@interface SSNViewController ()
@end

@implementation SSNViewController
@synthesize collectionViewPack;
static NSString * const kCellReuseIdentifier = @"collectionViewCell";

- (void)viewDidLoad
{
    [self.collectionViewPack registerNib:[UINib nibWithNibName:@"CollectionViewItem" bundle:nil] forCellWithReuseIdentifier:kCellReuseIdentifier];
    self.collectionViewPack.backgroundColor = [UIColor redColor];

    [super viewDidLoad];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(100, 100)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [self.collectionViewPack setCollectionViewLayout:flowLayout];
    [self.collectionViewPack setAllowsSelection:YES];
    self.collectionViewPack.delegate=self;
}

// collection view data source methods ////////////////////////////////////
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 100;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellReuseIdentifier forIndexPath:indexPath];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
    [titleLabel setText:[NSString stringWithFormat:@"%d",indexPath.row]];

    return cell;

}

#pragma mark - delegate methods
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    printf("Selected View index=%d",indexPath.row);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

I think this is the only place may you get stucked. CollectionViewItem is an xib file in the project resource with a UILabel in it. please check the UICollectionView example project so you will get a clear cut idea about it. 🙂

 [self.collectionViewPack registerNib:[UINib nibWithNibName:@"CollectionViewItem" bundle:nil] forCellWithReuseIdentifier:kCellReuseIdentifier];
UICollectionView Final Output

UICollectionView Final Output

Download here
[box type =”download”]
“You can download the uicollectionview Example Project from here”. feel free to post your comments 
[/box]

References
[box]
UICollectionView class reference
[/box]

Please test the application in iOS 6 device/Simulator & comment here if you needs any help

5 Comments

  1. test January 25, 2013
  2. nn September 28, 2013
  3. Ahmad Durrani September 30, 2013
  4. Guru November 25, 2013
  5. safilsunny November 28, 2013

Leave a Reply

Your email address will not be published. Required fields are marked *