Understanding Collection View controllers and Collection View cells

As noted earlier in the book, Collection View Controllers allow us to display our data in a grid. The individual items inside of Collection Views are called cells, and these cells are what show our data. This data can be anything from an image to text, or both an image and text. You have complete control over what your Collection View cell can display. Our Collection View Controller is responsible for making sure the correct number of cells is displayed.

Let's now connect our file, ExploreViewController, with our UICollectionView in the storyboard. To do this, we use the Assistant Editor (or split screen), which we access by doing the following:

  1. Open Explore.storyboard.
  2. Close the Navigator panel using the hide Navigator toggle or command + O.
  3. Close the Utilities panel by hitting the Utilities toggle or use command + alt + O.
  4. Select the Assistant Editor or use command + alt + enter.

You should now see Explore.storyboard on the left and ExploreViewController.swift on the right:

  1. Add the following inside of your ExploreViewController.swift file on the line after the following code:
class ExploreViewController: UIViewController {
@IBOutlet weak var collectionView:UICollectionView!

IBOutlet is a way to a connect to the UI element. We have a Collection View on our UIViewController; now, we are creating a variable that allows us to hook into it.

  1. After you create the variable, you should see a small circle to the left of the variable:
  1. When you hover over it, you should see a plus button appear inside of the circle:

Click on it and drag this to your Collection View inside of your UIViewController:

  1. Once you release the mouse button, you should see the circle become filled:
  1. Select the Standard Editor or use command + enter.

In your scene, select your Collection View. Then, in your Utilities Panel, select the Connections inspector, which is the last icon on the right. Under the Outlets section, we now add back dataSource and delegate, the same ones we removed earlier:

The dataSource property is what is used to supply the data for our Collection View, so we need to pass whatever data we have to this property. On the other hand, the delegate property, which supplies the behavior, does not require us to supply anything as it receives interactions that happen within our Collection View. 

We need to update our data source for our Collection View; let's add this now:

  1. Click and drag the dataSource property to the Explore View Controller in your Outline view:

  1. Click and drag the delegate property to the Explore View Controller in your Outline view:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.178