-
Notifications
You must be signed in to change notification settings - Fork 1
I 5.2. Assigning a Data Source to a Collection View
Assign a data source to the collection view using the dataSource property of the UICol lectionView class. Your data source has to be an object that conforms to the UICollectionViewDataSource protocol, and it goes without saying that your data source object has to implement the required methods/properties of that protocol.
The data source of the collection view, like that in table views, is responsible for pro‐ viding enough data to the collection view so that it can render its contents on the screen. The way things are rendered on the screen is not the data source’s job. That is the layout’s job. The cells that the layout displays on your collection view will ultimately be provided by your collection view’s data source.
Here are the required methods of the UICollectionViewDataSource protocol that you have to implement in your data source:
collectionView:numberOfItemsInSection: This method returns an NSInteger that dictates to the collection view the number of items that should be rendered in the given section. The given section is passed to this method as an integer that represents the zero-based index of that section. This is the same in table views.
collectionView:cellForItemAtIndexPath: Your implementation of this method must return an instance of the UICollection ViewCell that represents the cell at a given index path. The UICollectionView Cell class subclasses the UICollectionReusableView class. In fact, any reusable cell given to a collection view to render must either directly or indirectly subclass UICollectionReusableView, as we will see later in this chapter. The index path will be given to you in the cellForItemAtIndexPath parameter of this method. You can query the section and the row indexes of the item from the index path.
Let’s go into the collection view controller’s implementation file (ViewController.m) that we created in the Recipe 5.1, and implement the aforementioned collection view data source methods:
#import "ViewController.h"
@implementation ViewController
/* For now, we won't return any sections */
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section{
return 0;
}
/* We don't yet know how we can return cells to the collection view so
let's return nil for now */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
return nil;
}
@end
The code is complete for now, but if you remember from Recipe 5.1, if you try to run this code, it will crash because the app delegate is setting the layout object of the collection view to nil. This problem is still there and will be solved in Recipe 5.3.