3
votes

I have a problem when I try to use a CollectionView into UIView.

This is the code example of my view.

class CampanasView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

class func create() -> CampanasView {
    let nib = UINib(nibName: "CampanasView", bundle: nil)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as? CampanasView

    //if you use xibs:
    view?.collectionView.register(UINib(nibName: "CampanaCell", bundle: nil), forCellWithReuseIdentifier: "CampanaCell")
    view?.collectionView.reloadData()
    return 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: "CampanaCell", for: indexPath) as! CampanaCell


    return cell
}

}

This is the xib

Xib File of the UIView

In my ViewController I have this code to add UIView into ViewController

var campanasView: CampanasView?

override func viewDidLoad() {
    super.viewDidLoad()


    self.campanasView = CampanasView.create()
    _ = JAutolayouts.fillContainer(self.contentView, view: self.campanasView!)
}

This is the error.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[WinUp.CampanasView collectionView:numberOfItemsInSection:]: unrecognized selector sent to class 0x10beac100'

1
can you post how is your setup for your CampanasView xib file? - Reinier Melian
Also, who calls your create() and when? - Smartcat
try this: add in viewDidLoad method collectionView.DataSource = self - Shabbir Ahmad
@Smartcat the method create() I use when instance the view into ViewController - Josué H.
Yes I set a datasource and delegate into de xib @user1000 - Josué H.

1 Answers

3
votes

Your issue is related to the setup of your xib, you need unlink your collection view delegate and datasource from your fileOwner and add this two lines in your create method

    view?.collectionView.dataSource = view
    view?.collectionView.delegate = view

And as I said above you need unlink datasource and delegate of your CollectionView

enter image description here

your create method must be like this

class func create() -> CampanasView {
        let nib = UINib(nibName: "CampanasView", bundle: nil)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as? CampanasView

        //if you use xibs:
        view?.collectionView.register(UINib(nibName: "CampanaCell", bundle: nil), forCellWithReuseIdentifier: "CampanaCell")
        view?.collectionView.dataSource = view
        view?.collectionView.delegate = view
        view?.collectionView.reloadData()
        return view!
    }