繁体   English   中英

向 UICollectionView 添加静态单元格

[英]Adding a static cell to a UICollectionView

我有一个 UICollectionView 显示数组中的单元格。 我希望第一个单元格是一个静态单元格,作为进入创建流程的提示(最终添加一个新单元格)。

我的方法是将两个部分添加到我的 collectionView,但我目前无法弄清楚如果我这样做,如何在 cellForItemAtIndexPath 中返回一个单元格。 这是我的尝试:

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
    }
}

这样做的问题是我必须在函数的末尾返回一个单元格。 似乎它不会作为 if 条件的一部分返回。 感谢您的帮助!

详细说明 Dan 的评论,该函数必须返回UICollectionViewCell的实例。 目前,编译器可以看到indexPath.section既不是 0 也不是 1 的代码路径。如果发生这种情况,您的代码将不返回任何内容。 这在您的应用程序中永远不会合乎逻辑地发生并不重要。

修复它的最简单方法是将“else if”更改为“else”。 如:

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
    }
}

现在如果只有两个代码路径,并且都返回一个单元格,那么编译器会更开心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM