Today you’ll learn how to do the following:
- How to display section headers
- How to display collection view cells below section headers
- How to highlight the Collection View Cell the user tapped
I’ve created an application we we’ll use to implement above requirements. So in order to follow along, you’ll have to download it by clicking the image shown here. Once you’ve unzip the file, drag-and-drop the GreekAlphabets folder in the iOS7 Projects folder on your Mac.
Overview of The Application
The iOS application you downloaded has only one storyboard file. Figure A and B below shows what it look like in Interface Builder and the iPad simulator. Further more, I created the scene by simply dragging a Collection View Controller from the Object Library and drop it on the storyboard.
Figure 1A | Figure 1B |
I set these properties for the Collection View.
The Collection View will be populated with custom Collection View Cells. The cells’ data are held in a data source object called, flashcardImagesFront and it is initialized with two arrays of image names, as shown in this image.
The MasterViewController Class
It is for adding code that’ll make the storyboard’s Master View Controller Scene functional. I’ve already created and connected it to the storyboard scene, via the Identity Inspector, as shown in the image below.
The MasterViewController class files contain code shown below. We’ll be adding more code in both files shortly.
The FlashcardCell Class
It is for creating Collection View Cells and I’ve already created and connected it to the Collection View Cell via the Identity Inspector. I’ve already set the cell’s Identifier attribute as well.
The FlashcardCell class files contain code shown below, and we won’t be adding any more code in them.
Add a Section Header and Label
What we have to do now is add a section header above the Collection View Cell, then add a Label in it. Click the Storyboard, select the Collection View object. In the Attributes inspector, tick the Section Header checkbox. Once enabled, the header view appears above the Collection View Cell, as shown in the image below.
Now, drag a Label from the Object Library and drop it on the Section Header. In the Attributes Inspector, change the attributes shown in the image below for the Label.
Switch to the Size Inspector and set properties shown in the image below for the Label.
Create a Class for The Section Header
Like the Collection View Cell, we have to create a class for the Reusable View (Section Header). Start by adding an Objective-C class in the project. Provide option shown in this image for the class.
Return to the storyboard and click the Collection Reusable View. In the Identity Inspector, connect the class to the Collection Reusable View object.
Switch over to the Attributes Inspector and enter “headerView” in the Identifier box.
Declare and Connect An Outlet for The Label
The Label we added in the Collection Reusable View will display a section header; so we have to use the Assistant Editor to declare and connect an outlet property for it in the HeaderView.h file.
Display section headers
to display section headers in the Collection Reusable View object, you’ll have to do the following.
Click the MasterViewController.m file add this import statement.
#import "HeaderView.h"
Scroll down to line 40 and replace it with code shown below.
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { //1. Create and initialize an instance of our HeaderSupplimentaryView class HeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind: kind withReuseIdentifier:@"HeaderView" forIndexPath:indexPath]; if (kind == UICollectionElementKindSectionHeader) { //2. Set the Label control's text attribute headerView.lblHeader.text = [[NSString alloc]initWithFormat: @"Greek Alphabets Flashcards - Set %i", indexPath.section + 1]; } //3. Return our headerView object return headerView; }
The viewForSupplimentaryElementOfKin method create and display a header in the Label control we placed in the Collection Reusable View object (section header).
Run
Now is a good time as any to run the application. Here’s what you’ll see in the iPad Simulator.
The reason why you’re seeing a section header in the Collection Reusable View’s Label control is because the app assume there’s only one section in the Collection View; even though we didn’t implement the numberOfSectionsInCollectionView: method in the MasterViewController.m file.
OK, we want to display two section headers in the Collection Reusable View’s Label control, so we’ll have to implement the numberOfSectionsInCollectionView: method in the MasterViewController.m file. Add the method below line 36.
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView { return 2; }
After implement the method, run the application and you’ll see two section headers now, instead of one.
Display Collection View Cells Below Section Headers
It is time to display items in Collection View Cells below section headers. To do that, you’ll have to set up the Collection View’s data source object in the MasterViewController class, then implement the Collection View’s data source methods. Start by adding this code in the MasterViewController.h file.
// This array holds front view of flashcard images @property(nonatomic, strong) NSArray *flashcardImagesFront;
Next, add this code in the ViewDidLoad method.
// Create and initialize two arrays with image names NSArray *flashcardSet1 = @[@"alpha-front.png", @"vita-front.png", @"gamma-front.png", @"thelda-front.png", @"epsilon-front.png", @"zita-front.png"]; NSArray *flashcardSet2 = @[@"ita-front.png", "theta-front.png", @"iota-front.png", @"kappa-front.png", @"lamdha-front.png" @"mi-front.png"]; // Add above arrays as elements of the flashcardImagesFront array self.flashcardImagesFront = @[flashcardSet1,flashcardSet2];
You’ve setup the Collection View’s data source object; what you have to do now is, implement the Collection View’s data source methods in the MasterViewController.m file.
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { // Count and return the total number of images a section contain return [[_flashcardImagesFront objectAtIndex:section] count]; } - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { // Initialize the reusable Collection View Cell FlashcardCell *flashcardCell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; // Create and initialize an image object with an image from the flashcardsFront array UIImage *image = [UIImage imageNamed:[_flashcardImagesFront[indexPath.section] objectAtIndex:indexPath.row]]; // Add the image in the imageView control flashcardCell.imageView.image = image; // Return the Collection View Cell return flashcardCell; }
After adding above code in the MasterViewController class files, run the application and you’ll see this output in the simulator.
As you can see images we added in the Collection View’s data source object, flashcardImagesFront are shown in below each section’s header.
Highlight The Collection View Cell The User Tapped
To highlight the Collection View Cell the user tapped, you’ll have to add these methods in the MasterViewController.m file. Add them below the cellForItemAtIndexPath: method.
// This method highlight the Collection View Cell the user tapped in a light yellow color - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; } // This method unhighlight the previously tapped Collection View Cell - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{ UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; cell.backgroundColor = [UIColor clearColor]; }
Once you’ve implemented above methods in the MasterViewController.m file, run the application and you’ll see the same output as shown in the image above; however, when you click a Collection View Cell, a yellow box will appear around the image. An example of this is shown in the image below.
That’s the end of today’s Collection View tutorial. In it you learned how to do the following:
- How to display section headers
- How to display collection view cells below section headers
- How to highlight the Collection View Cell the user tapped