Populating UICollectionView with images is returning nil : Swift 2

Jimmy lemieux

I have a UICollectionView with a custom cell with an UIImageView in it as well as a custom class with the outlet

class theCell: UICollectionViewCell { 
@IBOutlet var theImage:UIImageView!
}

I have an array of UIImage (Which only has one constant image). The image is in the main bundle.

var tempImages = [UIImage(named: "placeholder.png" )]

delegate methods

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

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

    let cell = self.collectionView?.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! theCell

    //Unexpectadly found nil
    cell.theImage.image = tempImages[indexPath.row]   
    return cell   
}
Dharmesh Kheni

If you have added this line:

self.collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "cell")

then remove this first and here is complete working code:

CollectionViewController.swift

import UIKit

class CollectionViewController: UICollectionViewController {

    var tempImages = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tempImages.append(UIImage(named: "bg.jpg")!)
    }

    // MARK: UICollectionViewDataSource

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


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

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

        // Configure the cell
        cell.theImage.image = tempImages[indexPath.row]
        println(cell.theImage.image)
        return cell
    }
}

CollectionViewCell.swift

import UIKit

class CollectionViewCell: UICollectionViewCell {


    @IBOutlet var theImage:UIImageView!

}

And don't forget to assign Identifier to your cell:

enter image description here

Sample for more Info.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related