Type 'ViewController' does not conform to protocol 'UICollectionViewDataSource'
Asked Answered
P

4

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?

Perusse answered 26/9, 2014 at 16:44 Comment(0)
V
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)

Vondavonni answered 11/10, 2014 at 12:34 Comment(2)
for me it was the '!' after each argument in the cellForItemAtIndexPath functionGeorgenegeorges
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.Boaz
L
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#>
}
Loos answered 19/7, 2018 at 11:30 Comment(0)
C
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:
Cowans answered 26/9, 2014 at 16:55 Comment(0)
L
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

Logos answered 4/5, 2017 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.