如何在 numberofitemsinsection 中管理两个不同的单元格

How can I manage two different cells in numberofitemsinsection

我想创建一个包含两个不同单元格的 collectionView。第一个单元格应该显示一次,第二个单元格应该在数组很大时显示。结果应该类似于附件 link 中的图像。这也是一个示例代码,可以更好地理解我的问题。感谢所有帮助我的人!!!

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


    switch indexpath { // No indexpath in numberofitemsinsection!
    case 0:
        return 1 //display one time the first cell
    default:
        return images.count // display as often as the array is large the second cell
    }

}

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    switch indexPath.row {
    case 0:
        let cell = imageCollectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath)
        return cell
    default:
        let cell = imageCollectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCell

           cell.imageView.image = images[indexPath.row] 

        cell.delegate = self
        cell.selectedAtIndex = indexPath

        return cell
    }
}

Here is the collectionView I want to create

你为什么不用这个?

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1 + theArray.count
}

您可以在 cellForItemAt 中实现这一点,您需要像下面这样更改 numberOfItemsInSection

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // return 1 more than our data array (the extra one will be the "add item" cell)
    return dataSourceArray.count + 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // if indexPath.item is less than data count, return a "Content" cell
    if indexPath.item < dataSourceArray.count {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! ContentCell

        // configure your ContentCell: cell. <attribute>

        return cell
    }

    // past the end of the data count, so return an "Add Item" cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddItemCell", for: indexPath) as! AddItemCell

    // configure your AddCell: cell. <attribute>

    return cell

}

为此你需要创建一个 ContentCellAddItemCell 并且还有一个 dataSourceArray 来存储你需要的所有数据。