Sunday, January 24, 2016

Objective C UICollectionView Layouts

We know that for a list data we have UITableView, UIScrollView for display purpose.

Using UIScrollview, we can display both in horizontal and vertical directions. Whereas, using UITableView, we can only display list data vertical direction. Having said that, populating list data in UIScrollView needs loads of mathematical calculations for arranging data items (Images, views, labels etc) properly with alignment.

UICollectionView is the best choice If you are populating a list data and you need to change the direction of scroll even at run time. It is very handy compared to UITableView and UIScrollView.


Unlike the UITableView and UIScrollview, UICollectionView needs a layout at the time of initialization. In this layout we tell the direction of the data display and all. If we don't set a non nil layout parameter, You will end up with a crash throwing the below error.

"UICollectionView must be initialized with a non-nil layout parameter"

If you are placing the UICollectionView control in the XIB and giving the connection, There you will be having to set the layout parameter.

There are two types of layouts available.

  • Flow
  • Custom

Flow is the default layout as shown below.

  UICollectionViewFlowLayout *collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];      
  [collectionViewLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
  UICollectionView  *collectionView = [[UICollectionView alloc]       
            initWithFrame:CGRectMake(0,0,200,300) collectionViewLayout:collectionViewLayout];  


We can also subclass UICollectionView layout and give it as custom class in the XIB or as shown below when initializing programatically.

  HomeCollectionViewFlowLayout *kCollViewLayout = [[HomeCollectionViewFlowLayout alloc]init];
  [kCollViewLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
  UICollectionView  *collectionView = 
             [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,200,300) kCollViewLayout];     

Here, HomeCollectionViewFlowLayout is my custom class which I subclassed from UICollectionViewFlowLayout class.

Hope this post is useful. Feel free to comment incase of any queries.