maidi
maidi

Reputation: 3459

Collection View Cells not appearing

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

Upvotes: 18

Views: 39394

Answers (14)

livingSwiftly
livingSwiftly

Reputation: 11

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
}

Upvotes: 1

Dave Dempsey
Dave Dempsey

Reputation: 115

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

Upvotes: 0

Nikhil Chandra
Nikhil Chandra

Reputation: 163

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

    cell.isHidden = false

Upvotes: 1

Asad Mehmood
Asad Mehmood

Reputation: 359

I removed this code from my CollectionViewController.m file

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

and cell get appeared

Upvotes: 4

Hamid Reza Ansari
Hamid Reza Ansari

Reputation: 1147

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

helpful image link

Upvotes: 2

Ges83
Ges83

Reputation: 82

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

Upvotes: 4

Pavel Smejkal
Pavel Smejkal

Reputation: 3599

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

Upvotes: 16

Rushang Prajapati
Rushang Prajapati

Reputation: 596

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

Upvotes: 1

Subash
Subash

Reputation: 1000

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

enter image description here

Upvotes: 2

Bhavin Kansagara
Bhavin Kansagara

Reputation: 2916

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

Upvotes: 3

William Hu
William Hu

Reputation: 16149

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

enter image description here

Upvotes: 1

rkyr
rkyr

Reputation: 3241

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
}

Upvotes: 1

Kannan Chandrasegaran
Kannan Chandrasegaran

Reputation: 81

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.

Upvotes: 1

Subash
Subash

Reputation: 1000

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.

Upvotes: 4

Related Questions