Xcode - UICollectionView inside UIViewController

I am trying to embed a collection view inside a UIViewController:

import UIKit

class imagesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var labels = ["label1", "label2", "label3"]

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = UIColor.redColor()

        collectionView.delegate = self
        collectionView.dataSource = self

    }




    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        //#warning Incomplete method implementation -- Return the number of sections
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //#warning Incomplete method implementation -- Return the number of items in the section
        return labels.count
    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! UICollectionViewCell

        // Configure the cell

        var title = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height))
        cell.contentView.addSubview(title)

        title.text = labels[indexPath.row]
        title.textColor = UIColor.yellowColor()

        return cell
    }

      

The application starts up, but the collection view doesn't seem to be properly bound to the class, none of the configurations I've done just show up. Oddly enough, I had to copy / paste functions to represent the collection because autocomplete only shows some of the collection methods.

+3


source to share


1 answer


If you created your cells with StoryBoard then I had the same problem and was able to solve it by deleting

self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

      



This row, if you defined a cell in the StoryBoard, seems to be a duplicate effort and will block any of the cells from being displayed.

+2


source







All Articles