Search code examples
xcodeuilabelnsunknownkeyexception

Xcode How can I fix the error linking my uilabel to xib file?


I'm using a xib file to create the cells for a couple collection views on the main page of my IOS app. The cell created in the xib file contains 3 ImageView elements and I recently added a UILabel. After adding the UILabel element to the cell, I created an outlet to the controlling file. Thus allowing me access to the element from the UIViewController file. Now whenever I build and run the app I get the following error:

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

My initial research of the error lead me to the conclusion that I should delete the outlet to the label. Which makes no sense to me because then how will I control the label's content programmatically from the view controller? The only other conclusion I can come to is that I don't need an outlet for a UILabel. Can anyone explain or confirm my assumption? Here is the code to which I created the outlet and where the label.text is being called.

Global_CVCCell

class Global_CVCCell: UICollectionViewCell
{
@IBOutlet weak var cell_Label: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var highlightIndicator: UIImageView!
@IBOutlet weak var selectionIndicator: UIImageView!

View Controller

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 
-> UICollectionViewCell
{
    if collectionView == self.REDACTED
    {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as? Global_CVCCell

        myCell?.cell_Label.text = dataForREDACTED[indexPath.row].name
        myCell!.backgroundColor = UIColor.red
        myCell?.imageView.image = UIImage.circle(diameter: 15, color: randomizeColor())

        return myCell!

    }

Thanks for any help that y'all can provide!

  • UserC-137

Solution

  • This exception is not coming from ViewController class. This is coming from your collection View Cell. So you need to make sure your Cell IBOutlet variable should be connect with the XIB UI component.