Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

UICollectionViewCell not appearing


I'm creating a UICollectionView programmatically.

As a disclaimer, I followed this tutorial: http://randexdev.com/2014/07/uicollectionview/

So my setup is as follows:

I have a storyboard with a UIScrollView which is controlled by ViewControllerA.

In a separate class CustomCollectionViewController I have the following code:

import Foundation
import UIKit

class CustomCollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 90, height: 120)

        super.init(collectionViewLayout: layout)

        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        //collectionView = UICollectionView(frame: CGRectMake(0, 0, 500, 500), collectionViewLayout: layout)
        collectionView!.dataSource = self
        collectionView!.delegate = self
        collectionView!.backgroundColor = UIColor.redColor()
        collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        self.view.addSubview(collectionView!)
    }

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

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 14
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.greenColor()
        return cell
    }
}

In my ViewControllerA I have this code

let collectionViewController: CustomCollectionViewController = CustomCollectionViewController(nibName: nil, bundle: nil)
collectionViewController.view.frame.origin = CGPointMake(scrollViewWidth*3, 0)

scrollView.addSubview(collectionViewController.view)

If run in the simulator, I can see the red background of the UICollectionView, but no cells whatsoever.

Any hints what I'm doing wrong?


Solution

  • The problem was that I didn't set the ViewController as childViewController in the viewControllerA

    self.addChildViewController(collectionViewController)
    collectionViewController.didMoveToParentViewController(self)