16

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

maidi
  • 3,219
  • 6
  • 27
  • 55
  • It might be an auto layout issue if you are using storyboard. Can you show the screenshot of the view controller on storyboard and also the screnshots of the layout options? – Subash Nov 23 '15 at 22:24
  • I tried with auto layout disabled and there still was the same problem. What do you mean with the layout options? I added a screenshot of the view controller on storyboard – maidi Nov 23 '15 at 22:34
  • Have you remembered to set the custom class of the controller in the StoryBoard to your CollectionViewController? – Michael Nov 26 '15 at 04:45
  • Have you check if your " func collectionView(collectionView: UICollectionView, numberOfItemsSection section: Int) " is executing? – nigelman Nov 30 '15 at 23:51
  • Is your UIViewController inside a UITabBarController? Can you please check if this question is related to yours: http://stackoverflow.com/q/33177968/1171404 – Sebastian Krogull Dec 01 '15 at 10:31
  • It looks harmful... `var Array = [String]()`. – Wanbok Choi Dec 02 '15 at 09:21

14 Answers14

16

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

Pavel Smejkal
  • 3,600
  • 6
  • 27
  • 45
4
func layoutCells() {
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
        layout.minimumInteritemSpacing = 5.0
        layout.minimumLineSpacing = 5.0
        layout.itemSize = CGSize(width: (UIScreen.mainScreen().bounds.size.width - 40)/3, height: ((UIScreen.mainScreen().bounds.size.width - 40)/3))
        collectionView!.collectionViewLayout = layout
    }

Try this. Call this function from view did load. I think the problem is that your collection is not laid out correctly.

func viewDidLoad() {
    layoutCells()
}

If this works you can modify the layout options to meet your needs.

Subash
  • 1,002
  • 13
  • 26
4

I had a similar problem, I found this that was somehow restraining the size of my cell. Hope this helps.

Select the CollectionViewCell

Find this values in size inspector

smottt
  • 3,272
  • 11
  • 37
  • 44
Ges83
  • 82
  • 6
4

I removed this code from my CollectionViewController.m file

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

and cell get appeared

Asad Mehmood
  • 341
  • 2
  • 12
3

Problem is with setting the title to button, use the following code.

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]
        button.setTitle(Array[indexPath.row], forState: UIControlState.Normal)
        return cell
}

Hope it helps

Bhavin Kansagara
  • 2,866
  • 1
  • 16
  • 20
2

Make sure you have the correct reuse identifier set for the cell.

enter image description here

Subash
  • 1,002
  • 13
  • 26
2

check that you are setting CollectionView outlets (datasource , delegate) in your storyBoard as show below

helpful image link

ascripter
  • 5,665
  • 12
  • 45
  • 68
Hamid Reza Ansari
  • 1,107
  • 13
  • 16
1

Ideas:

  • Check if your cell reuse identifier is set up.
  • Check if you've set the collection view subclass correctly in the storyboard.
  • Put print statements inside your cellForItemAtIndexPath function to see if it's being called ever.
  • Not sure if this should be an issue, but Array is actually a type in Swift. Using that as your variable name might be messing with the logic somehow. Rename it to array (lowercase). I believe this is best practice for variable names anyway.
  • Do something else to the cell in cellForItemAtIndexPath, such as changing the background color. If that works, maybe there's just something wrong with what you're doing with tags.
1

Your problem is in

func collectionView(collectionView: UICollectionView, numberOfItemsSection section: Int)

method signature. It is wrong. It should be

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int

and with override specification (because UICollectionViewController has own, this why you get empty collection).

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  return Array.count
}
rkyr
  • 3,131
  • 2
  • 23
  • 38
1

First of all check you have used this method:-

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return searches.count
}

There’s one search per section, so the number of sections is the count of the searches array. so also we can use as per needed this method.by default we can use retuen 1

And Follow step in the Link for better soluation Check this link

  • The default implementation for the protocol returns 1 so it can't be it. – Tomasz Bąk Dec 02 '15 at 17:17
  • ohh yes @TomaszBąk There’s one search per section, so the number of sections is the count of the searches array. so also we can use as per needed this method.And thank you correction because its help other to better understand. – Rushang Prajapati Dec 03 '15 at 05:00
1

Select the UIButton in storyboard, check the installed as the bottom left in the image below.

enter image description here

William Hu
  • 15,423
  • 11
  • 100
  • 121
1

Check to make sure that the cell is not hidden. Add this code below

    cell.isHidden = false
Nikhil Chandra
  • 163
  • 1
  • 2
  • 10
1

I know i'm 7 years late but for people researching this issue...Here's the answer.

The cell was probably showing but because it wasn't configured properly , the button did not appear.

NOTE: For new developers, if you add anything to a cell (CollectionView/TableView) through storyboard you won't be able to change the values programmatically unless you create a custom cell and connect the storyboard cell to the custom cell. Then you'll have to connect the button from storyboard cell to the custom cell.

Judging by the posted problem code, The cell was not configured at all.

Study the posted problem with notes added by me to identify the errors that were made.

STEP BY STEP SOLUTION

INCORRECT

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

// cell was declared as a UICollectionViewCell, which is basically a default empty cell. It should have been declared as a custom cell.

CORRECTION

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CustomCollectionViewCell

//developer was trying to pass a cell as a button, which is telling Xcode that the cell is the same as the button which would cause a crash since that's not possible and it was forced unwrapped (as!). Another thing is that the button was created but never added to the cell, so it's a siting duck.

var button = cell.viewWithTag(1) as! UIButton

ENTIRE SOLUTION

Create a new file/custom cell and connect it to the storyboard cell using the identity inspector. See image below

Image

Connect the button from storyboard to the custom cell, then create a function to configure the button

class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var button:UIButton!

    func configureCell() {

        button.setTitle("Custom Text", for: .normal)
    }

}

Now within the cellForItem func.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
    
    cell.configureCell()
    
    return cell
}
0

The items in the cell weren't showing up for me because I hadn't set tamic for each of the added subviews when programmatically adding subviews.

subview.translatesAutoresizingMaskIntoConstraints = false
Dave Dempsey
  • 117
  • 3
  • 7