Collection View Cells not appearing in Collection

2019-09-11 08:15发布

问题:

I created a Collection View using purely the storyboard interface builder. This is what the storyboard looks like:

My collection view's properties are default as well. I haven't written anything into my ViewController.swift yet.

For some reason, when I run on my phone / emulator, none of the buttons are showing.

回答1:

Just configure the collectionView properly see below code and image:

Implement the delegate methods of collectionView:

class yourClassController: UICollectionViewDataSource, UICollectionViewDelegate {

override func numberOfSectionsInCollectionView(collectionView: 
    UICollectionView!) -> Int {
    return 1
}

override func collectionView(collectionView: UICollectionView!, 
    numberOfItemsInSection section: Int) -> Int {
    return yourArray.count
}

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

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

     // Configure the cell
     cell.backgroundColor = UIColor.blackColor()
     cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
     cell.imageView?.image = UIImage(named: "circle")



    return cell
}

Then from your storyboard set the delegate and datasource by drag and drop see image:

Note: collectionView appears when you do complete above formality with its relevant class.



回答2:

UICollectionView does not support static cells like UITableView. You will have to set its dataSource,delegate and configure your cells in code.