I asked a similar question last week but I think I have it narrowed down to more specifically what is going wrong. The custom cell is being loaded and looks to be called correctly when I use the collectionView.dequeReusableCellWithIdentifier("MenuCell", forIndexPath: indexPath) as MenuCollectionViewCell
"MenuCell" is the reuse identifier for my custom cell and MenuCollectionViewCell is the swift file that holds the custom code. From debugging the code I have determined that the UIImageView is not being loaded. I did a check and that is what I came up with. Why the ImageView is not being loaded and is only appearing as nil I do not know. I will post the code for the file where it is being loaded and the custom cell code.
class MenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate
{
// Not sure if I really need this
@IBOutlet var menuCollectionView: MenuCollectionView!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view
view.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: "behind_alert_view.png"))
// This was the fix here
self.menuCollectionView.delegate = self
self.menuCollectionView.dataSource = self
}
// Variables
var menuImagesArray = ["MyProfileIcon.png"]
// Data Source Protocol
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return menuImagesArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
var menuCell: MenuCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MenuCell", forIndexPath: indexPath) as MenuCollectionViewCell
var image: UIImage!
if ((menuCell.imageView) != nil)
{
image = UIImage(named: menuImagesArray[indexPath.row])
}
menuCell.imageView.image = image
return menuCell
}
}
And here is the custom cell file:
class MenuCollectionViewCell: UICollectionViewCell
{
@IBOutlet var imageView: UIImageView!
}
The error that I am receiving is a termination due to unwrapping a nil value for an optional. The problem is the UIImageView for sure, any help figuring this out would be great!
EDIT/SOLVED
The problem was the connection to the UICollectionView. I had the reference to it but I had not used it properly. I was trying to set the dataSource and delegate in the storyboard and that seemed to be the problem for me. When I moved over to the code and made the reference and referenced it in the way I did with those two calls it instantly fixed it. I hope this can help someone else if they run into the same problem! Now on to customizing it since it pops up!