Beginning UICollectionView in iOS 6

Audio : Listen to This Blog.

Introduction about CollectionView :

Collection Views are a powerful new technology in iOS 6 that allow content to be presented using arbitrary layouts & introduce presenting multiple items on the screen using layouts. This feature is most promptly used by the

UI design companies

in creating the user friendly interface. Collection view used to represent its content onscreen, collection view cooperates with many different objects. For example, your app must provide a data source object that tells the collection view how many items there are to display. Other objects are provided by UIKit and are part of the basic collection view design.
Your app is strictly responsible for managing the data to be presented but many different objects manage the visual presentation.The patterns for providing data to a UICollectionView to create items and interact with those items follow the same delegation and data source patterns commonly used in iOS development.

UI UX Design

What is UICollectionView?
  • A collection view is used to represent data in a grid view manner i.e. In rows and columns. Getting layouts like grid view was possible even then and is possible even now but now its quite simple as compared to before using UICollectionView
  • A collection view can have its own custom layouts
  • The class UICollectionViewController has mainly 3 important parts
    Cell

      – a cell is used to represent an item in collection view

    Supplementary View

      – can be used to show data like header/footer or block of text

    Decoration View

      – if you want to add some extra view to enhance the visual appearance of the UICollectionView ,then decoration view should be used
UICollectionView and UITableView
  • UICollectionView and UITableView are similar but not in all aspects
  • These two classes differ in representation. Using UITableView data can be represented only vertically, you can have only number of rows but not number of columns whereas in UICollectionView you can have number of rows as well as number of columns. In other words we can say that UICollectionView is horizontal representation of UITableView

These two classes are similar in data source,delegate and registering nib/class aspects
In UICollectionView nib/class can be registered as
//using class
[self.collectionViewregisterClass:[UICollectionViewCellclass] forCellWithReuseIdentifier:@"Cell"];
//using nib
UINib *cellNib = [UINibnibWithNibName:yourNibNamebundle:nil];
[self.collectionViewregisterNib:cellNib forCellWithReuseIdentifier:identifier];
In UITableView nib/class can be registered as
//using nib
[self.tableViewregisterNib:[UINibnibWithNibName:yourNibNamebundle:nil] forCellReuseIdentifier:identifier];
//using class
[self.reusableViewregisterClass:[UITableViewCellclass] forCellReuseIdentifier:identifier];

Note:

before in data source method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; we used to check a condition i.e.
if(cell == nil) {
cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:myIdentifier];
}
but now there is no need of checking this condition as we register class , so even if there will be no cell in the queue to be reused , the one instance will be instantiated automatically.
Now its time to show one simple demo. There is source code attached named

CollectionViewDemo

which shows just number of cells in matrix form with a label on cells.
First select a SingleView Template, Use Automatic Reference Counting checkbox should be checked. Name your project as required. I have given CollectionViewDemo. In ViewController.xib , drag and drop UICollectionView on the already existing view. Set the delegate by right clicking on UICollectionView. In ViewController.m file make an IBOutlet as collectionView. In ViewController.h file just add UICollectionViewDataSource , UICollectionViewDelegate protocols.
Now add one class subclassing UICollectionViewCell and name it accordingly. I have given CollectionViewCell. Once you create this you will get CollectionViewCell.h/.m files.
In CollectionViewCell.h take one label property.
In CollectionViewCell.m,
- (id)initWithFrame:(CGRect)frame{
self = [superinitWithFrame:frame];
if (self) {
self.label = [[UILabelalloc]initWithFrame:CGRectMake(5, 5, 40,20)];
self.label.text = @"hello";
self.label.backgroundColor = [UIColorclearColor];
self.label.textAlignment = NSTextAlignmentCenter;
[self.contentViewaddSubview:self.label];
}
returnself;
}
Here the label is added to the contentView of the cell as cell is having different subviews like backgroundView, selectedBackgroundView and contentView.
In ViewController.h, import the CollectionViewCell class.
Now in ViewController.m, in viewDidLoad() , register class for reusing cell
//registering class for cell reusing
[self.collectionViewregisterClass:[CollectionViewCellclass] forCellWithReuseIdentifier:@"CollectionCell"];
And then implement the data source methods. Datasource methods provide the information for collectionview. UICollectionView will call the datasource methods to get the information.
// This api is used to return number of items in each section of collection view
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return10;
}
// This api is used to return number of sections in collection view
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return5;
}

cellForItemAtIndexPath

is used to configure each item of collection view. UICollectionView class will only call its data source to get Cells for items that are on the screen. Cells that scroll off the screen are placed in to a queue for reuse. Same technique is used to Supplementaryview as well.
when making the call to dequeueReusableCellWithReuseIdentifier , where the Cell will be either dequeued from the reuse queue, if a Cell is not available, iOS 6 will create it automatically based upon the type or nib that was registered.
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell"forIndexPath:indexPath];
cell.backgroundColor = [UIColorredColor];

return cell;
}
ok so now you are ready to run the project….
That was just simple example. Now what if you want to have header/footer kind of thing in your app. So no need to worry about that is also simple as well.

Supplementary views:

Supplementary Views are views that present information associated with each section of a UICollectionView (supplementary views are data driven). However, supplementary views are not mandatory and their usage and placement is controlled by the layout object being used. For example, the flow layout supports headers and footers as optional supplementary views.
Supplementary Views are more generic than just headers and footers. They can be positioned anywhere in the collection view and can be comprised of any views, making their appearance fully customizable.

  • Register supplementary views similar to cells
  • GetViewForSupplimentaryElement return view
  • DequeueReuseableSupplimentary view creates view
  • Supplementary View inherits from UICollectionReusableView

Add one class name it as required. I have given SupplementaryView which subclasses
UICollectionReusableView. You will get two files as SupplementaryView.h/.m.
In ViewController.h , import the SupplementaryView class.
In ViewController.m, in viewDidLoad(), register the SupplementaryView class for reuse.
//registering class for view reusing
[self.collectionViewregisterClass:[SupplementaryViewclass] forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"SupplementaryView"];
Your implementation of viewForSupplementaryElementOfKind this method is responsible for creating, configuring, and returning the appropriate supplementary view that is being requested. The placement of supplementary views is handled automatically by the layout object.
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
SupplementaryView *supplementaryView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SupplementaryView"forIndexPath:indexPath];
if(kind == UICollectionElementKindSectionHeader){
supplementaryView.backgroundColor = [UIColorgreenColor];
supplementaryView.label.text = @"Header";
}
return supplementaryView;
}
Asks the delegate for the size of the header view in the specified section, we can override referenceSizeForHeaderInSection method. If you do not implement this method, the flow layout uses the value in its headerReferenceSize property. During layout only the size that corresponds to the appropriate scrolling direction is used.
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
return CGSizeMake(supplimentaryViewWidth, 50); //here supplimentaryViewWidth will be set automatically depending on iPhone/iPad app even if you give any value for this.
}
okay, so now lets run the project.
You can see the number of sections,  items in each section  & supplementary view as sections header.

Note :

the size of the cell can be changed in nib file and the scrolling direction too i.e. You want horizontally or vertically.
Here is the sample code. Go and explore it.
CollectionViewDemo

Read Similar Blogs