Understanding the data source

Whenever we use Collection View to get data, we must conform to a protocol. A protocol is a set of methods to which we have access, and can either be required or optional. For Collection Views, we are required to implement three methods to get data into a Collection View. So, let's add the following four functions (each beginning with func) after the closing curly bracket of viewDidLoad():

Let's break down the code to better understand what we are doing:

  • Part AThis first method is what we need to add a header to our Collection View:
collectionView(_:viewForSupplementaryElementOfKind:at:)
  • Part BThe identifier is what we added when we were designing in earlier chapters. This identifier helps Xcode know what view we are referring to:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
return headerView
  • Part COur next method gets called for every item we need. Therefore, in our case, it gets called 20 times:
collectionView(_:cellForItemAt:)

  • Part DHere, we are creating a cell every time collectionView(_:numberOfItemsInSection:) is called. The identifier, exploreCell, is the name we gave it in the storyboard; so, this is the cell that is grabbed and used inside of our Collection View:
return collectionView.dequeueReusableCell(withReuseIdentifier: "exploreCell", for: indexPath)
  • Part EThis method tells our Collection View how many different sections we want to display:
numberOfSections(in collectionView: UICollectionView)
  • Part F: Here, we are telling our Collection View that we only want one section:
return 1
  • Part GOur next method tells our Collection View how many different items we are going to display inside of the section we set up:
collectionView(_:numberOfItemsInSection:)
  • Part HWe are telling our Collection View that we want to display 20 items:
return 20
  • Part IFinally, we add this line back as it was removed. We use this function to dismiss our location modal when you hit the Cancel button:
@IBAction func unwindLocationCancel(segue:UIStoryboardSegue) {}

Let's build and run the project by hitting the Play button (or using command + R). We are now finished.

..................Content has been hidden....................

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