In this chapter, you will continue working on the Photorama application by displaying the interesting Flickr photos in a grid using the UICollectionView class. This chapter will also reinforce the data source design pattern that you used in previous chapters. Figure 21.1 shows you what the application will look like at the end of this chapter.
In Chapter 10, you worked with UITableView. Table views are a great way to display and edit a column of information in a hierarchical list. Like a table view, a collection view also displays an ordered collection of items, but instead of displaying the information in a hierarchical list, the collection view has a layout object that drives the display of information. You will use a built-in layout object, the UICollectionViewFlowLayout, to present the interesting photos in a scrollable grid.
Let’s tackle the interface first. You are going to change the UI for PhotosViewController to display a collection view instead of displaying the image view.
Open Main.storyboard and locate the Photorama image view. Delete the image view from the canvas and drag a Collection View onto the canvas. Select both the collection view and its superview. (The easiest way to do this is using the document outline.) Open the Auto Layout Align menu, configure it like Figure 21.2, and click Add 4 Constraints.
Because you used the Align menu to pin the edges, the collection view will be pinned to the top of the entire view instead of to the top layout guide. This is useful for scroll views (and their subclasses, like UITableView and UICollectionView) so that the content will scroll underneath the navigation bar. The scroll view will automatically update its insets to make the content visible, as you saw in Chapter 10. The canvas will now look like Figure 21.3.
Currently, the collection view cells have a clear background color. Select the collection view cell – the small rectangle in the upper-left corner of the collection view – and give it a black background color.
Select the black collection view cell and open its attributes inspector. Set the Identifier to UICollectionViewCell (Figure 21.4).
The collection view is now on the canvas, but you need a way to populate the cells with data. To do this, you will create a new class to act as the data source of the collection view.