Search code examples
iosswiftuicollectionviewuicollectionviewcell

How can I manage two different cells in numberofitemsinsection


I want to create a collectionView with two different cells. The first cell should be displayed one time and the second should be displayed as often as the array is large. The result should be something like in the image in the attached link. Here is also a example code for better understanding my problem. Thanks to everyone who helps me!!! 🙂

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


Solution

  • You can achieve this inside cellForItemAt and you need to change numberOfItemsInSection like below:

    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
    
    }
    

    For that you need to create a ContentCell and AddItemCell and also have a dataSourceArray to store all data you need.