The main objective of this blog post is to show How to create a custom cell in UICollectionView.
UICollectionView and show the data in a simple grid like layout. Very similar to table views, collection views brings together a set of cells. Each cell is represented by the
UICollectionViewCell class.UICollectionView class offers developers the flexibility to present items in a grid view. You’ll see the basic steps for defining a collection view and a custom cell layout.
1) Create a new Xcode project.
Create a new XCODE project and select single view application and name it as CollectionViewDemo.
2) Design UI
Go to Main.Storyboard and add a Collection View from the object library.
3) Connect the Delegate, datasource and make the outlet.
4) Set the size
Set the size of cell from the size inspector in right panel and its Reuseidzntifier as shown below.
5) Design Custom cell.
Design a Custom cell by adding an image view and label or whatever is required on cell in the same way as done below.
6) Create a Custom class
Create a custom class of UICollectionViewCell and name it as CustomCell.
7) Linking class with your cell
Assign the custom class name to your cell as shown
Make internal connections of image view and label taken on cell in your custom class.
9) Implement Delegate methods
Implement the required delegate methods of collectionView in your Controller class and drop an image in your project bundle that you want to show in collection view cell.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
Above delegate method returns the number of cells you need to display in your collection view.
- (CGSize)collectionView:(UICollectionView *)collectionView
The above delegate method is optional and it is only to adjust width and height of cell for all devices.
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
CustomCell* cell = [cv dequeueReusableCellWithReuseIdentifier:@“MyCell” forIndexPath:indexPath];
cell.backgroundColor = [UIColor clearColor];
cell.LabelName.text = @“Developer”;
cell.ImgView.image = [UIImage imageNamed:@“Image.png”];
In above method, an image dropped in project bundle by name Image.png is given to the Imageview taken on cell and text is assigned on label.
The delegate method highlighted in blue is only to set the width and height of cell which can also be done from the size inspector.
10) Run your application
Today we learnt How to create a custom cell in UICollectionView.I hope you find this blog very helpful while working with Custom cell Using UICollectionView.