Collection View Cells not appearing

maidi picture maidi · Nov 23, 2015 · Viewed 28k times · Source

I want to display as many collectionViewCells with buttons as there are strings in my array. but when I start the simulator there is just the background of the CollectionViewbut no cells shown. What could be the error?

Here is the code from my CollectionViewController that I attached to the CollectionView in the main.storyboard:

class CollectionViewController: UICollectionViewController {

var Array = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    Array = ["1","2","3","4","5"]
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsSection section: Int) -> Int {
    return Array.count
}

override func
    collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! UICollectionViewCell

        var button = cell.viewWithTag(1) as! UIButton
        button.titleLabel?.text = Array[indexPath.row]

        return cell
}

}

These are the connections of the Collection View Controller:

connections

The View Controller on the Storyboard:

viewcontroller

Answer

Pavel Smejkal picture Pavel Smejkal · Nov 26, 2015

Did you set the CollectionViewController to the storyboard identity inspector? :)

And I would try to call the reloadData() after you change the data in the viewDidLoad method.

Hope that helps