user3092406
user3092406

Reputation: 13

UICollectionView created in .xib is nil Swift

The collectionView always is nil, I created it in .xib. Crash occurs in the first interaction with the collectionView Thank you in advance.

This is the error. fatal error: unexpectedly found nil while unwrapping an Optional value

class ChannelsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate  {

    var managedObjectContext: NSManagedObjectContext? = AppDelegate.sharedAppDelegate().managedObjectContext;

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView.delegate = self
        self.collectionView.dataSource = self

        self.collectionView.registerNib(UINib(nibName:"ChannelsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
    }
}

Upvotes: 1

Views: 2506

Answers (1)

Yhondri
Yhondri

Reputation: 944

The problem for me was that I was not loading the nib. Try this.

init() {
    super.init(nibName: "ChannelsViewController", bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
} 

override func viewDidLoad() {
    super.viewDidLoad()

    self.collectionView.delegate = self
    self.collectionView.dataSource = self

    self.collectionView.registerNib(UINib(nibName:"ChannelsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
}

Upvotes: 1

Related Questions