Adding a static cell to a UICollectionView

痴心易碎 提交于 2019-12-24 16:29:01

问题


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!


回答1:


Elaborating on Dan's comment, the function must return an instance of UICollectionViewCell. At the moment the compiler can see a code path where indexPath.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:

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 { // This means indexPath.section == 1
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("mainCell", forIndexPath: indexPath) as! MainCollectionViewCell
        cell.imageView?.image = self.imageArray[indexPath.row]
        return cell
    }
}

Now if there are only two code paths, and both return a cell, so the compiler will be happier.



来源:https://stackoverflow.com/questions/36146462/adding-a-static-cell-to-a-uicollectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!