简体   繁体   中英

[UIView collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance

I seem to be getting the following error in Xcode:

[UIView collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance

The following is my code:

import UIKit

class RestaurantListViewController: UIViewController, UICollectionViewDataSource {
    
    @IBOutlet var collectionView:UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "restaurantListCell", for: indexPath)
        return cell
    }

}

My cell identifier reflected in the utilities panel is: restaurantListCell

Any help would be much appreciated.

Zack

Swift 5

This kind of problems often occur due to neglecting some of very basics rule that people sometime even can't think of, Give it a code review using this checklist:

  1. First of all your class should be inherited with UICollectionViewDelegate, UICollectionViewDataSource.

  2. CollectionView outlets should be set

  3. CollectionView Datasource & Delegate should be connected through storyboard or with in viewDidLoad

  4. Check if you have connected the storyboard with the corresponding viewcontroller class.

  5. check for no of rows count and cellForItemAt array count. if it's equal or not.

  6. Finally check for any flow layout class if you are using any in Storyboard. it should be connected also.

我遇到了同样的错误,问题是我没有在我的视图控制器中连接集合视图出口,我没有在故事板中为我的视图控制器提供类名。

I am not sure whether the problem is still relevant given the post is 5 months old, but I just encountered a very similar error message in one of my projects. In my case, the problem was that the view controller class did not conform both the UICollectionViewDataSource and UICollectionViewDelegate protocols.

If you add the UICollectionViewDelegate protocol to your code, it should work hopefully.

Best, Fanni

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