0

I'm trying to add a collection view of some images within an array defined inside the view did load method. The app builds and runs fine but when I navigate to this specific section called "Portfolio" the app crashes giving me this in the console.

fatal error: unexpectedly found nil while unwrapping an Optional value

Can anyone figure out from the code below what is happening? I've tried wrapping the issue in an if statement and that keeps it from crashing but then the images won't display at all. If I simply define a UIBackgroundColor it works like it should.

import UIKit

class PortfolioView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

var array:[String] = []

override func viewDidLoad() {

    array = ["PortImage1","PortImage2","PortImage3","PortImage4","PortImage5","PortImage6","PortImage7"]


    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

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


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

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

    cell.imageView.image = UIImage(named: array[indexPath.row])


    cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2
    cell.imageView.clipsToBounds = true


    cell.imageView.layer.borderWidth = 2.0
    cell.imageView.layer.borderColor = UIColor.whiteColor().CGColor


    return cell


}

}

Andy Leverenz
  • 11
  • 1
  • 1

2 Answers2

0

On the face of it, and just guessing because you have not provided any of the relevant information, it appears that you've defined a class CollectionViewCell which has an imageView property, but you have failed to hook up any image view in the storyboard / nib by an outlet to that imageView property. Thus, at load time, your imageView property is nil.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Oddly enough I had it hooked up but Xcode must of not of recognized it. I went to re-establish the connection and it worked. Thanks – Andy Leverenz May 15 '15 at 14:10
0

In your case cell is unable to find imageView and crashes as it finds it as nil. Give tag say "100" to your imageView in the storyboard. Then add following line to your code after you dequeue the cell as follows :-

let imageView = cell.viewWithTag(100) as! UIImageView imageView.image = UIImage(named: array[indexPath.item])

Ishika
  • 2,187
  • 1
  • 17
  • 30