Making a GridView in iOS using UICollectionView.

By | November 23, 2014

Hey all,

In Today’s article you will study about the implementation of UICollectionView in iOS.
It is similar to GridView in Android.

UICollectionView in iOS

First drag a UICollectionView [Not the Collection View Controller] in your interface and let it be there.
we will come back to it later.

We are going to create a UICollectionView with custom Cells.

So for that we will first create a class for the Custom Rows in the UICollection.
For that Go to Project->right Click-> Add new File -> Cocoa files -> name it “CustomCollectionCell” and extends UICollectionViewCell

UICollectionView in iOS

CustomCollectionCell.h

#import <UIKit/UIKit.h>

@interface CustomCollectionCell : UICollectionViewCell
{
   
}

@property (nonatomic, strong) IBOutlet UILabel *collectionLabel;
@property (nonatomic, strong) IBOutlet UIImageView *collectionImage;

@end

CustomCollectionCell.m

#import "CustomCollectionCell.h"

@implementation CustomCollectionCell

@end

Now you will notice that there will be a new UICollection row in the hierarchy of the interface in which
the UICollectionView is placed.

UICollectionView in iOS

Now after selecting the cell row from the hierarchy go to the attributes inspector and set the class
name as “CustomCollectionCell” as shown in the Screenshot below.

UICollectionView in iOS

Also set the “identifier” as “CollectionCell”.

UICollectionView in iOS

Now place an “ImageView” and “Label” inside the label and connect it to the variables in the CustomCollectionCell,collectionImage and collectionLabel.

Now we will go to the controller that implements the UICollectionView.

Like TableViews UICollectionView also has delegate methods.

So Add the delegate to the ViewController.h

We will set the Datasource and Delegate in the code itself.

ViewController.h



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>{
   
    NSArray *image_array, *label_array;
    
}

@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;


@end

In the above code we have a variable for the UICollectionView, so please hook it to the outlet before proceeding otherwise you will see nothing in the interface.

ViewController.m

#import "ViewController.h"
#import "CustomCollectionCell.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize collectionView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    image_array = [NSArray arrayWithObjects: @"apple.png", @"android.png", @"apple.png", @"android.png",@"apple.png", @"android.png",@"apple.png", @"android.png", nil ];
    label_array = [NSArray arrayWithObjects: @"APPLE", @"ANDROID",@"APPLE", @"ANDROID", @"APPLE", @"ANDROID",
                   @"APPLE", @"ANDROID", nil ];
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    CGRect rect = collectionView.frame;
    rect.origin.x = 5;
    rect.origin.y = 0;
    rect.size.width = [[UIScreen mainScreen] bounds].size.width - 5;
    rect.size.height = [[UIScreen mainScreen] bounds].size.height;
    
    collectionView.frame = rect;
    
    collectionView.backgroundColor = [UIColor clearColor];
}


-(void) setBorder:(UIView *) theView withBGColor:(UIColor *) color withCornerRadius :(float) radius andBorderWidth :(float) borderWidth andBorderColor :(UIColor *) bgColor WithAlpha:(float) curAlpha
{
    theView.layer.borderWidth = borderWidth;
    theView.layer.cornerRadius = radius;
    theView.layer.borderColor = [color CGColor];
    UIColor *c = [color colorWithAlphaComponent:curAlpha];
    theView.layer.backgroundColor = [c CGColor];
}

#pragma mark - UICollectionView Datasource
// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [image_array count];
}
// 2
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}
// 3
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"CollectionCell";
    
    CustomCollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    cell.collectionLabel.text = [label_array objectAtIndex:indexPath.row];
    cell.collectionImage.image = [UIImage imageNamed: [image_array objectAtIndex:indexPath.row]];
    
    if(indexPath.row % 2 == 0)
        [self setBorder:cell withBGColor:[UIColor greenColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    else
        [self setBorder:cell withBGColor:[UIColor redColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    
    return cell;
}
// 4
/*- (UICollectionReusableView *)collectionView:
 (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
 {
 return [[UICollectionReusableView alloc] init];
 }*/


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Clicked %d", indexPath.row);
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

}

#pragma mark – UICollectionViewDelegateFlowLayout

// 1
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize s = CGSizeMake([[UIScreen mainScreen] bounds].size.width/2 - 8, [[UIScreen mainScreen] bounds].size.height/2-70);
    return s;
}

// 3
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 0, 5, 5);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

All done, Just go on and run the application.

You can download the complete source code from here.