简体   繁体   中英

Type 'ViewController' does not conform to protocol 'UICollectionViewDataSource'

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?

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 {}

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

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#>
}

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM