Lets take a quick look at Collection Views and how to set them up.
First, lets set up the storyboard. We’ll need the following things:
- UICollectionView — Drag it onto the story board
- UIImageView — Drag and drop the Image View inside the UICollectionViewCell
- Set the CollectionViewCell Identifier to “Cell”
Now lets create some classes, and set them accordingly in the storyboard.
- Create the CollectionViewController — We’ll be typing most of our code here
- Create the CollectionViewCell to hold the images
- Create an IBOutlet for the UIImageView
// CollectionViewCell.h
// UICollectionViewBlog
// Created by Val Osipenko on 7/24/15.
// Copyright (c) 2015 Val Osipenko. All rights reserved.
//#import <UIKit/UIKit.h>
@interface CollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *sleepyImageView;
@end
The code part:
Set up NSArray to hold the images that we will be displaying:
#import “CollectionViewController.h”
@interface CollectionViewController ()@property (nonatomic, strong) NSArray *flatironSleepsImages;@end@implementation CollectionViewControllerstatic NSString * const reuseIdentifier = @”Cell”;
- (void)viewDidLoad {
[super viewDidLoad];self.flatironSleepsImages = @[@”1.jpg”,@”2.jpg”,@”3.jpg”,@”4.jpg”,@”5.jpg”,@”6.jpg”,@”7.jpg”,@”8.jpg”,@”9.jpg”];// Register cell classes
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];}
Set the “numberOfSectionsInCollectionView” and “numberOfItemsInSection”
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.flatironSleepsImages.count;
}
And finally lets set the images to display in the collection view cells:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];cell.sleepyImageView.image =[UIImage imageNamed:[self.flatironSleepsImages objectAtIndex:indexPath.row]];
return cell;
}
Lets build it:
Ran out of time: Next blog topic?
Custom UICollectionView Layouts: