I have a UICollectionView that displays cells from an array. I want the first cell to be a static cell that serves as a prompt to segue into a create flow (eventually adding a new cell).
My approach would have been to add two sections to my collectionView, but I currently can't figure out how to return a cell within cellForItemAtIndexPath if I do so. This is my attempt:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let firstCell = collectionView.dequeueReusableCellWithReuseIdentifier("createCell", forIndexPath: indexPath) as! CreateCollectionViewCell
firstCell.imageView.backgroundColor = UIColor(white: 0, alpha: 1)
return firstCell
} else if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("mainCell", forIndexPath: indexPath) as! MainCollectionViewCell
cell.imageView?.image = self.imageArray[indexPath.row]
return cell
}
}
The problem with this is that I have to return a cell at the end of the function. It seems that it won't be returned as part of an if condition. Thanks for helping!
Elaborating on Dan's comment, the function must return an instance of
UICollectionViewCell
. At the moment the compiler can see a code path whereindexPath.section
is neither 0 nor 1. If this occurs, your code returns nothing. It doesn't matter that this will never occur logically in your app.The easiest way to fix it is to just change the "else if" to an "else". As in:
Now if there are only two code paths, and both return a cell, so the compiler will be happier.