Search code examples
iosswiftuiviewuicollectionviewxib

xib with UICollectionView - not key value coding compliant


I have a Custom UIView with an XIB. This custom UIView has a UICollectionView which is connected to an IBOutlet. In the view setup, the UICollectionView is initialised properly and is not nil.

However in the cellForItemAtIndexPath method, I get this error:-

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key selectorCollectionView.'

If I remove the datasource and delegate, I do not get any error. If I add them Iget an error at this line:-

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectorCell", for: indexPath) as! SelectorCell

Please help!

Edit: I have attached screenshots of my setup

The custom view is added to a UITableViewCell

The custom view has this collectionview

I have set the class for the cell

and the identifier

I have uploaded the project here too http://www.fast-files.com/getfile.aspx?file=148623


Solution

  • Maybe a sync issue. Happens sometimes:

    1. Try cut outlets loose and reconnect them.

    2. Make sure Collection Reusable View identifier is defined in xib file: Set identifier here

    3. Make sure collection-view cell's custom class is define in xib file:

    Set custom class here

    EDIT: I dug into your project and here are my findings

    UICollectionView should be init' in awakeFromNib method (override it):

    override func awakeFromNib() {
        super.awakeFromNib()
        let cellNib = UINib(nibName: String(describing: "SelectorCell"), bundle: nil)
        selectorCollectionView.register(cellNib, forCellWithReuseIdentifier: "selectorCell")
        selectorCollectionView.dataSource = self
        selectorCollectionView.delegate = self
    }
    

    loadViewFromNib should be looking like this (Remove collection view init'):

    func loadViewFromNib() -> UIView {
        let nib = UINib(nibName: "SelectorView", bundle: nil)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        return view
    }
    

    Subclass SelectorTableViewCell likewise.

    class SelectorTableViewCell: UITableViewCell {
        @IBOutlet weak var selectorView: SelectorView!
    }
    

    In Main.storyboard - custom class UITableViewCell to SelectorTableViewCell and connect SelectorView inside contentView to 'SelectorTableViewCell''s outlet.

    That's it i think. Here is the project: