Lontronix
Lontronix

Reputation: 193

IBOutlet Nil in UITableViewCell .Xib file

In my UITableViewCell sub class called Cell, all of the IBOutlets I attach from the corresponding Xib file are nil and result in the app crashing with the error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the line where I attempt to access a property of the IBOutlet. the File's Owner of the .Xib file is set to cell and so is the UITableViewCell in the .Xib file

Code:

import UIKit

class Cell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource {

@IBOutlet weak var label: UILabel! (CONNECTED TO .XIB FILE)

override func awakeFromNib() {
    super.awakeFromNib()
    viewDidLoad()
    print(label.text)//APP CRASHES HERE!
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

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

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

}

}

Upvotes: 0

Views: 1195

Answers (1)

Muhammad Shauket
Muhammad Shauket

Reputation: 2778

Your inside view did not connected with your file owner, so make a IBOutlet property.

@IBOutlet private var contentView: UIView!

connect this with the main view of xib file as a refrence outlet.

and inside this function of your custom class

@objc required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! commonInit() // write this to load nib file }

in commonInit() load your nib from bundle and add your contentview as commonInit()

Upvotes: 1

Related Questions