16

I am following a tutorial where using the UIPickerController to operate the camera. However when implementing UICollectionViewDatsaSource, I get an error saying that ViewController does not conform to the UICollectionViewDataSource protocol.

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

Any idea on how to fix this problem?

Wain
  • 118,658
  • 15
  • 128
  • 151
RPMouton
  • 161
  • 1
  • 1
  • 6

4 Answers4

33

You must implement this two method in your ViewController class:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {}

P.S. - Your function prototype should exactly match with above functions.(remove any '!' if present)

Aks
  • 8,181
  • 5
  • 37
  • 38
  • 1
    for me it was the '!' after each argument in the cellForItemAtIndexPath function – Chris Oct 21 '14 at 11:32
  • It seems like with Swift the default behavior is a red error for not implementing the required protocol methods, whereas in Objective-C Xcode just gives a yellow warning. You have to at least stub out the required methods to make the error go away. – James Kuang Nov 16 '15 at 02:14
3

You have to implement these two method in your ViewController class for Collection View :

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    <#code#>
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    <#code#>
}
2

Adding the protocol definition to your custom class is not enough. You have to provide the required functions of the protocol. See the documenation of the protocol, you have to implement at least:

collectionView:numberOfItemsInSection:
collectionView:cellForItemAtIndexPath:
zisoft
  • 22,770
  • 10
  • 62
  • 73
0

The UICollectionViewDataSource has two functions must be implemented!(they are required functions of the protocol).

To fix the problem,just implement the two functions like this: enter image description here

渠晓友
  • 11
  • 2